Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
70 changes: 45 additions & 25 deletions packages/transformers/src/models/marian/tokenization_marian.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ export class MarianTokenizer extends PreTrainedTokenizer {
constructor(tokenizerJSON, tokenizerConfig) {
super(tokenizerJSON, tokenizerConfig);

this.languageRegex = /^(>>\w+<<)\s*/g;
this.languageRegex = /^(>>\w+<<)\s*/;

this.supported_language_codes = Array.from(this.get_vocab().keys()).filter((x) => this.languageRegex.test(x));

Expand All @@ -25,32 +25,52 @@ export class MarianTokenizer extends PreTrainedTokenizer {
}

/**
* Encodes a single text. Overriding this method is necessary since the language codes
* must be removed before encoding with sentencepiece model.
* @see https://github.com/huggingface/transformers/blob/12d51db243a00726a548a43cc333390ebae731e3/src/transformers/models/marian/tokenization_marian.py#L204-L213
* Splits the language code (e.g., `>>fr<<`) off the start of the text, since it
* must be removed before encoding with the sentencepiece model.
* @see https://github.com/huggingface/transformers/blob/v4.57.1/src/transformers/models/marian/tokenization_marian.py#L185-L196
*
* @param {string|null} text The text to encode.
* @returns {string[]|null} The encoded tokens.
* @param {string} text The text to split.
* @returns {[string|null, string]} The language code (or `null` if the text does not start with one) and the remaining text.
* @private
*/
_encode_text(text) {
if (text === null) return null;

// Check if text starts with language code:
const [matchInfo, ...remainder] = text.trim().split(this.languageRegex);

if (remainder.length === 0) {
// No language code, encode normally
return super._encode_text(matchInfo);
} else if (remainder.length === 2) {
// Text starts with language code, so we do not encode it with sentencepiece.
const [language, text] = remainder;

if (!this.supported_language_codes.includes(language)) {
logger.warn(
`Unsupported language code "${language}" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`,
);
}
return mergeArrays([language], super._encode_text(text));
_split_language_code(text) {
const match = text.match(this.languageRegex);
if (match === null) {
return [null, text];
}
const language = match[1];
if (!this.supported_language_codes.includes(language)) {
logger.warn(
`Unsupported language code "${language}" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`,
);
}
return [language, text.slice(match[0].length)];
}

/**
* @type {PreTrainedTokenizer['_encode_plus']}
* @protected
*/
_encode_plus(text, options) {
const [language, remainder] = this._split_language_code(text);
const encoded = super._encode_plus(remainder, options);
if (language !== null) {
encoded.input_ids.unshift(this.convert_tokens_to_ids(language) ?? this.unk_token_id);
encoded.attention_mask.unshift(1);
encoded.token_type_ids?.unshift(0);
}
return encoded;
}

/** @type {PreTrainedTokenizer['encode']} */
encode(text, options) {
return this._encode_plus(text, options).input_ids;
}

/** @type {PreTrainedTokenizer['tokenize']} */
tokenize(text, options) {
const [language, remainder] = this._split_language_code(text);
const tokens = super.tokenize(remainder, options);
return language === null ? tokens : mergeArrays([language], tokens);
}
}
2 changes: 1 addition & 1 deletion packages/transformers/src/tokenization_utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -544,7 +544,7 @@ export class PreTrainedTokenizer
* @param {boolean} [options.add_special_tokens=true] Whether or not to add the special tokens associated with the corresponding model.
* @param {boolean|null} [options.return_token_type_ids=null] Whether to return token_type_ids.
* @returns {{input_ids: number[], attention_mask: number[], token_type_ids?: number[]}} An object containing the encoded text.
* @private
* @protected
*/
_encode_plus(text, { text_pair = null, add_special_tokens = true, return_token_type_ids = null } = {}) {
const { ids, attention_mask, token_type_ids } = this._tokenizer.encode(text, {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
import { MarianTokenizer } from "../../../src/models/tokenizers.js";
import { BASE_TEST_STRINGS, MARIAN_TEST_STRINGS } from "../test_strings.js";

export const TOKENIZER_CLASS = MarianTokenizer;
export const TEST_CONFIG = {
"Xenova/opus-mt-en-ROMANCE": {
SIMPLE: {
text: BASE_TEST_STRINGS.SIMPLE,
tokens: ["\u2581How", "\u2581are", "\u2581you", "\u2581doing", "?"],
ids: [621, 63, 33, 951, 19, 0],
decoded: "How are you doing?</s>",
},
LANGUAGE_CODE: {
text: MARIAN_TEST_STRINGS.LANGUAGE_CODE,
tokens: [">>fr<<", "\u2581The", "\u2581weather", "\u2581is", "\u2581nice", "\u2581today", "."],
ids: [14, 46, 7032, 28, 2922, 1071, 3, 0],
decoded: ">>fr<< The weather is nice today.</s>",
},
LANGUAGE_CODE_WITH_REGION: {
text: MARIAN_TEST_STRINGS.LANGUAGE_CODE_WITH_REGION,
tokens: [">>es_MX<<", "\u2581Hello", "\u2581world"],
ids: [51471, 4708, 468, 0],
decoded: ">>es_MX<< Hello world</s>",
},
LANGUAGE_CODE_WITHOUT_SPACE: {
text: MARIAN_TEST_STRINGS.LANGUAGE_CODE_WITHOUT_SPACE,
tokens: [">>fr<<", "\u2581Hello"],
ids: [14, 4708, 0],
decoded: ">>fr<< Hello</s>",
},
LANGUAGE_CODE_NOT_AT_START: {
text: MARIAN_TEST_STRINGS.LANGUAGE_CODE_NOT_AT_START,
tokens: ["\u2581Hello", "\u2581>", ">", "fr", "<", "<", "\u2581world"],
ids: [4708, 658, 11862, 8844, 22829, 22829, 468, 0],
decoded: "Hello >>fr<< world</s>",
},
UNKNOWN_LANGUAGE_CODE: {
text: MARIAN_TEST_STRINGS.UNKNOWN_LANGUAGE_CODE,
tokens: [">>xx<<", "\u2581Hello"],
ids: [1, 4708, 0],
},
},
};

const MAX_EXECUTION_TIME = 10_000;
export const CUSTOM_TESTS = () => {
const model_id = "Xenova/opus-mt-en-ROMANCE";

it(
"should support every language code in the vocabulary",
async () => {
const tokenizer = await MarianTokenizer.from_pretrained(model_id);
const language_codes = Array.from(tokenizer.get_vocab().keys()).filter((x) => x.startsWith(">>") && x.endsWith("<<"));
expect(language_codes).toHaveLength(47);
expect(tokenizer.supported_language_codes).toEqual(language_codes);
},
MAX_EXECUTION_TIME,
);

it(
"should keep the language code when padding a batch",
async () => {
const tokenizer = await MarianTokenizer.from_pretrained(model_id);
const { input_ids, attention_mask } = tokenizer([">>fr<< Hello world", ">>es<< Hello"], { padding: true, return_tensor: false });
expect(input_ids).toEqual([
[14, 4708, 468, 0],
[16, 4708, 0, 65000],
]);
expect(attention_mask).toEqual([
[1, 1, 1, 1],
[1, 1, 1, 0],
]);
},
MAX_EXECUTION_TIME,
);
};
8 changes: 8 additions & 0 deletions packages/transformers/tests/models/test_strings.js
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,14 @@ export const M2M_100_TEST_STRINGS = {
CHINESE_TEXT: "生活就像一盒巧克力。",
};

export const MARIAN_TEST_STRINGS = {
LANGUAGE_CODE: ">>fr<< The weather is nice today.",
LANGUAGE_CODE_WITH_REGION: ">>es_MX<< Hello world",
LANGUAGE_CODE_WITHOUT_SPACE: ">>fr<<Hello",
LANGUAGE_CODE_NOT_AT_START: "Hello >>fr<< world",
UNKNOWN_LANGUAGE_CODE: ">>xx<< Hello",
};

// Test strings adapted from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/normalize
export const NORMALIZATION_TEST_STRINGS = {
DEFAULT_EXAMPLE: "\u0041\u006d\u00e9\u006c\u0069\u0065 | \u0041\u006d\u0065\u0301\u006c\u0069\u0065",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,4 +39,36 @@ export default () => {
await pipe?.dispose();
}, MAX_MODEL_DISPOSE_TIME);
});

describe("Translation (Marian model, target language codes)", () => {
const model_id = "Xenova/opus-mt-en-ROMANCE";

/** @type {TranslationPipeline} */
let pipe;
beforeAll(async () => {
pipe = await pipeline(PIPELINE_ID, model_id, { dtype: "q8" });
}, MAX_MODEL_LOAD_TIME);

it("should be an instance of TranslationPipeline", () => {
expect(pipe).toBeInstanceOf(TranslationPipeline);
});

describe("batch_size=1", () => {
it(
"translates into the language given by the language code",
async () => {
const text = "Hello, how are you?";
expect(await pipe(`>>fr<< ${text}`)).toEqual([{ translation_text: "Bonjour, comment allez-vous?" }]);
expect(await pipe(`>>es<< ${text}`)).toEqual([{ translation_text: "Hola, ¿cómo estás?" }]);
expect(await pipe(`>>it<< ${text}`)).toEqual([{ translation_text: "Ciao, come stai?" }]);
expect(await pipe(`>>pt<< ${text}`)).toEqual([{ translation_text: "Olá, como está?" }]);
},
MAX_TEST_EXECUTION_TIME,
);
});

afterAll(async () => {
await pipe?.dispose();
}, MAX_MODEL_DISPOSE_TIME);
});
};