Upload usage_guide.md

#7
Files changed (1) hide show
  1. usage_guide.md +692 -0
usage_guide.md ADDED
@@ -0,0 +1,692 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # How to use SalamandraTA models
2
+
3
+ <aside>
4
+
5
+ 📌 Location of our published models:
6
+
7
+ [🤗 SalamandraTA-7B - Full model](https://huggingface.co/BSC-LT/salamandraTA-7b-instruct)
8
+
9
+ → [7B Quantized version](https://huggingface.co/BSC-LT/salamandraTA-7B-instruct-GGUF)
10
+
11
+ [🤗 SalamandraTA-2B - Full model](https://huggingface.co/BSC-LT/salamandraTA-2b-instruct)
12
+
13
+ → [2B Quantized version](https://huggingface.co/BSC-LT/salamandraTA-2B-instruct-GGUF)
14
+
15
+ </aside>
16
+
17
+ ## Table of Contents
18
+
19
+ - [Introduction](#introduction)
20
+ - [Quick Start Guide - Full Models](#quick-start-guide---full-models)
21
+ - [Installation Requirements](#installation-requirements)
22
+ - [Loading the Model and Tokenizer in Python](#loading-the-model-and-tokenizer-in-python)
23
+ - [Preparing Your First Prompt](#preparing-your-first-prompt)
24
+ - [Generating a Translation (Inference)](#generating-a-translation-inference)
25
+ - [Quick Start Guide - Quantized Models](#quick-start-guide---quantized-models)
26
+ - [Installation Requirements](#installation-requirements-1)
27
+ - [Loading the Model and Tokenizer in Python](#loading-the-model-and-tokenizer-in-python-1)
28
+ - [Preparing Your First Prompt](#preparing-your-first-prompt-1)
29
+ - [Generating a Translation (Inference)](#generating-a-translation-inference-1)
30
+ - [Prompting Guide](#prompting-guide)
31
+ - [Multi-turn Prompts](#multi-turn-prompts)
32
+ - [Load the Model and Tokenizer](#load-the-model-and-tokenizer)
33
+ - [Define a Chat Helper Function](#define-a-chat-helper-function)
34
+ - [Example: Alternative Translations](#example-alternative-translations)
35
+ - [Notes on multi-turn interactions](#notes-on-multi-turn-interactions)
36
+ - [Decoding Strategies](#decoding-strategies)
37
+ - [Greedy Decoding (Default)](#greedy-decoding-default)
38
+ - [Beam Search](#beam-search)
39
+ - [Important Note on End Tokens](#important-note-on-end-tokens)
40
+ - [Diverse Beam Search](#diverse-beam-search)
41
+ - [Quality-Aware Decoding Strategies](#quality-aware-decoding-strategies)
42
+ - [Tuned Re-ranking](#tuned-re-ranking)
43
+ - [Minimum Bayes Risk (MBR) Decoding](#minimum-bayes-risk-mbr-decoding)
44
+ - [Compatibility Wrapper](#compatibility-wrapper)
45
+
46
+ ## Introduction
47
+
48
+ **SalamandraTA** is a family of multilingual language models fine-tuned for translation and related language technology tasks. These instruction-tuned variants (available in 2B and 7B sizes) are part of the broader Salamandra model suite and are particularly strong in **Catalan, Spanish, and English**, with support for over 40 languages.
49
+
50
+ The models support sentence- and paragraph-level translation, automatic post-editing, paraphrasing, grammar correction, and multilingual NER. Both models are available in full precision and quantized formats, making them accessible for a wide range of hardware configurations.
51
+
52
+ This document serves as a **wiki and quick start guide** for developers and researchers who want to use SalamandraTA for translation and MT-related tasks. It includes introductory notes on prompting, decoding strategies, and key technical specifications of the model.
53
+
54
+ <aside>
55
+
56
+ 📎 **Overview:**
57
+
58
+ - **Languages supported:** 40 languages (and 3 varieties)
59
+
60
+ Arabic, Aragonese, Asturian, Basque, Bulgarian, Catalan (and Catalan-Valencian variety), Chinese (simplified), Croatian, Czech, Danish, Dutch, English, Estonian, Finnish, French, Galician, German, Greek, Hindi, Hungarian, Irish, Italian, Japanese, Korean, Latvian, Lithuanian, Maltese, Norwegian (Bokmål and Nynorsk varieties), Occitan (and Aranese variety), Polish, Portuguese, Romanian, Russian, Serbian, Slovak, Slovenian, Spanish, Swedish, Ukrainian, Welsh
61
+
62
+ - **Tasks supported:** 9 translation and/or MT-related tasks
63
+
64
+ Sentence-level-translation
65
+ Paragraph-level-translation
66
+ Document-level-translation
67
+ Automatic post-editing
68
+ Grammar checking
69
+ Machine translation evaluation
70
+ Alternative translations
71
+ Named-entity-recognition
72
+ Context-aware translation
73
+
74
+ - **Architectures:**
75
+ - salamandraTA-2b-instruct
76
+
77
+
78
+ | **Feature** | **Value** |
79
+ | --- | --- |
80
+ | Total parameters | 2,253,490,176 |
81
+ | Embedding parameters | 524,288,000 |
82
+ | Layers | 24 |
83
+ | Hidden size | 2,048 |
84
+ | Attention heads | 16 |
85
+ | Context length | 8,192 |
86
+ | Vocabulary size | 256,000 |
87
+ | Precision | bfloat16 |
88
+ | Embeddig type | RoPE |
89
+ | Activation function | SwiGLU |
90
+ | Layer normalization | RMS Norm |
91
+ | Flash attention | ✅ |
92
+ | Grouped query attention | ❌ |
93
+ | Num. query groups | N/A |
94
+ - salamandraTA-7b-instruct
95
+
96
+
97
+ | **Feature** | **Value** |
98
+ | --- | --- |
99
+ | Total parameters | 7,768,117,248 |
100
+ | Embedding parameters | 1,048,576,000 |
101
+ | Layers | 32 |
102
+ | Hidden size | 4,096 |
103
+ | Attention heads | 32 |
104
+ | Context length | 8,192 |
105
+ | Vocabulary size | 256,000 |
106
+ | Precision | bfloat16 |
107
+ | Embeddig type | RoPE |
108
+ | Activation function | SwiGLU |
109
+ | Layer normalization | RMS Norm |
110
+ | Flash attention | ✅ |
111
+ | Grouped query attention | ✅ |
112
+ | Num. query groups | 8 |
113
+ - **Resource considerations:**
114
+ - Full models
115
+ - salamandraTA-2b-instruct
116
+
117
+ Loading the SalamandraTA-2b model requires approximately **4.5 GB of GPU memory** just for the weights. Additional memory is needed for intermediate computations, activations, and buffers.
118
+
119
+ For stable inference and to avoid out-of-memory errors, a GPU with at least **12 GB of VRAM** is recommended. Please see specifics below.
120
+
121
+ | **Resource** | **Requirement** | **Notes** |
122
+ | --- | --- | --- |
123
+ | Weights (bf16) | ~4.5 GB | From 2.25B params |
124
+ | KV cache (8192 ctx) | ~1.6 GB | Grows linearly with context length |
125
+ | Total minimal | ~6.1 GB | Weights + KV only |
126
+ | **Practical VRAM** | **≥12 GB** | |
127
+ | FLOPs/token | ~4.5B | ≈2 × params |
128
+ - salamandraTA-7b-instruct
129
+
130
+ Loading the SalamandraTA-7b model requires approximately **15.5 GB of GPU memory** just for the weights. Additional memory is needed for intermediate computations, activations, and buffers.
131
+
132
+ For stable inference and to avoid out-of-memory errors, a GPU with at least **24 GB of VRAM** is recommended. Please see specifics below.
133
+
134
+ | **Resource** | **Requirement** | **Notes** |
135
+ | --- | --- | --- |
136
+ | Weights (bf16) | ~15.5 GB | From 7.77B params |
137
+ | KV cache (8192 ctx) | ~4.3 GB | Grows linearly with context length |
138
+ | Total minimal | ~19.8 GB | Weights + KV only |
139
+ | **Practical VRAM** | **≥24 GB** | |
140
+ | FLOPs/token | ~15.5B | ≈3.45 × heavier than 2B |
141
+ - Quantized models
142
+ - salamandraTA-2b-instruct-GGUF
143
+
144
+ Loading the quantized SalamandraTA-2b model requires approximately **2.7 GB of GPU memory** just for the weights. Additional memory is needed for intermediate computations, activations, and buffers.
145
+
146
+ For stable inference and to avoid out-of-memory errors, a GPU with at least **8 GB of VRAM** is recommended. Please see specifics below.
147
+
148
+ | **Resource** | **Requirement** | **Notes** |
149
+ | --- | --- | --- |
150
+ | Weights (Q4, CPU) | ~2.7-3 GB | From 2.25B params quantized |
151
+ | KV cache (8192 ctx, FP16) | ~1.6 GB | Grows linearly with context length |
152
+ | Total minimal | ~4.3 GB | Weights + KV only |
153
+ | **Practical VRAM** | **≥8 GB** | |
154
+ | FLOPs/token | ~2.2B | ≈params × quantization overhead |
155
+ - salamandraTA-7b-instruct-GGUF
156
+
157
+ Loading the quantized SalamandraTA-2b model requires approximately **8.6 GB of GPU memory** just for the weights. Additional memory is needed for intermediate computations, activations, and buffers.
158
+
159
+ For stable inference and to avoid out-of-memory errors, a GPU with at least **16 GB of VRAM** is recommended. Please see specifics below.
160
+
161
+ | **Resource** | **Requirement** | **Notes** |
162
+ | --- | --- | --- |
163
+ | Weights (Q4, CPU) | ~8.6 GB | From 6.7B params quantized |
164
+ | KV cache (8192 ctx, FP16) | ~5 GB | Grows linearly with context length |
165
+ | Total minimal | ~13.6 GB | Weights + KV only |
166
+ | **Practical VRAM** | **≥16 GB** | |
167
+ | FLOPs/token | ~6.7B | ≈params × quantization overhead |
168
+ </aside>
169
+
170
+ ## Quick Start Guide - Full Models
171
+
172
+ This section guides users from installing the necessary tools to running your first translation task, regardless of experience level.
173
+
174
+ ### Installation Requirements
175
+
176
+ Ensure you have the required packages installed:
177
+
178
+ ```bash
179
+ pip install transformers accelerate sentencepiece
180
+ ```
181
+
182
+ ### Loading the Model and Tokenizer in Python
183
+
184
+ ```python
185
+ from transformers import AutoTokenizer, AutoModelForCausalLM
186
+ import torch
187
+
188
+ # Load model and tokenizer
189
+ model_id = "BSC-LT/salamandraTA-7b-instruct" # Can also use "BSC-LT/salamandraTA-2b-instruct"
190
+ tokenizer = AutoTokenizer.from_pretrained(model_id)
191
+
192
+ model = AutoModelForCausalLM.from_pretrained(
193
+ model_id,
194
+ device_map="auto", # Automatically selects GPU/CPU (recommended for seamless use)
195
+ torch_dtype=torch.bfloat16 # Use bfloat16 for faster inference (ensure hardware support)
196
+ )
197
+ ```
198
+
199
+ ### Preparing Your First Prompt
200
+
201
+ SalamandraTA models use a specific prompt format (ChatML) to understand instructions properly. This is how you prepare a prompt to translate text from Spanish to Catalan:
202
+
203
+ ```python
204
+ # Define your task
205
+ # These variables will change depending on the task (translation, NER, grammar correction, etc.)
206
+ source = "Spanish"
207
+ target = "English"
208
+ sentence = (
209
+ "Ayer se fue, tomó sus cosas y se puso a navegar. Una camisa, un pantalón vaquero "
210
+ "y una canción, dónde irá, dónde irá. Se despidió, y decidió batirse en duelo con el mar. "
211
+ "Y recorrer el mundo en su velero. Y navegar, nai-na-na, navegar."
212
+ )
213
+ # Prepare the input prompt using the standard instruction format
214
+ # see the Prompting Guide for recommended prompts for different tasks
215
+ text = (
216
+ f"Translate the following text from {source} into {target}.\n"
217
+ f"{source}: {sentence}\n"
218
+ f"{target}:"
219
+ )
220
+
221
+ # Structure the prompt using ChatML format
222
+ message = [{"role": "user", "content": text}]
223
+
224
+ prompt = tokenizer.apply_chat_template(
225
+ message,
226
+ tokenize=False, # Return plain string, not tokenized
227
+ add_generation_prompt=True # Add special token to signal model should begin generating
228
+ )
229
+
230
+ ```
231
+
232
+ ### Generating a Translation (Inference)
233
+
234
+ ```python
235
+ inputs = tokenizer.encode(
236
+ prompt,
237
+ add_special_tokens=False, # Don't add special tokens beyond what the ChatML template includes
238
+ return_tensors="pt" # Return as PyTorch tensor
239
+ )
240
+
241
+ input_length = inputs.shape[1] # Used to trim the prompt portion from the output
242
+
243
+ eos_tokens = [ tokenizer.eos_token_id, tokenizer.convert_tokens_to_ids("<|im_end|>") ]
244
+
245
+ outputs = model.generate(
246
+ input_ids=inputs.to(model.device), # Automatically move to CPU/GPU as needed
247
+ max_new_tokens=200, # Increase this for longer inputs (e.g., paragraph or doc-level translation)
248
+ eos_token_id=eos_tokens, # Use instruction-tuned stop token and pre-training stop token
249
+ num_beams=1, # 1 = greedy decoding (use num_beams > 1 to enable beam search)
250
+
251
+ pad_token_id=tokenizer.eos_token_id # Required for some models during beam search
252
+ )
253
+
254
+ translation = tokenizer.decode(
255
+ outputs[0, input_length:], # Skip the prompt when decoding
256
+ skip_special_tokens=True # Remove any lingering special tokens
257
+ )
258
+
259
+ print(translation)
260
+ ```
261
+
262
+ ## Quick Start Guide - Quantized Models
263
+
264
+ ### Installation Requirements
265
+
266
+ For inference with quantized models (GGUF), ensure you have the required packages installed:
267
+
268
+ ```bash
269
+ pip install huggingface_hub vllm torch
270
+ pip install llama-cpp-python
271
+ ```
272
+
273
+ ### Loading the Model and Tokenizer in Python
274
+
275
+ ```python
276
+ from huggingface_hub import snapshot_download
277
+ from vllm import LLM, SamplingParams
278
+
279
+ # Download the quantized GGUF model from Hugging Face
280
+ model_dir = snapshot_download(
281
+ repo_id="BSC-LT/salamandraTA-7B-instruct-GGUF", # Replace with the 2B repo if needed
282
+ revision="main" # Optional: pin to a specific version
283
+ )
284
+ # Choose which GGUF file to load; q4 is generally recommended
285
+ model_name = "salamandrata_7b_inst_q4.gguf"
286
+
287
+ # Load the quantized model and tokenizer for inference
288
+ llm = LLM(
289
+ model=model_dir + '/' + model_name, # Path to GGUF file
290
+ tokenizer=model_dir # Tokenizer is automatically detected from snapshot
291
+ )
292
+ ```
293
+
294
+ ### Preparing Your First Prompt
295
+
296
+ SalamandraTA models use a specific prompt format (ChatML) to understand instructions properly. This is how you prepare a prompt to translate text from Spanish to Catalan:
297
+
298
+ ```python
299
+ # Define your task
300
+ # These variables will change depending on the task (translation, NER, grammar correction, etc.)
301
+ source = "Spanish"
302
+ target = "English"
303
+ sentence = (
304
+ "Ayer se fue, tomó sus cosas y se puso a navegar. Una camisa, un pantalón vaquero "
305
+ "y una canción, dónde irá, dónde irá. Se despidió, y decidió batirse en duelo con el mar. "
306
+ "Y recorrer el mundo en su velero. Y navegar, nai-na-na, navegar."
307
+ )
308
+ # Prepare the input prompt using the standard instruction format
309
+ # see the Prompting Guide for recommended prompts for different tasks
310
+ prompt = f"Translate the following text from {source} into {target}.\\n{source}: {sentence} \\n{target}:"
311
+ messages = [{'role': 'user', 'content': prompt}]
312
+ )
313
+ ```
314
+
315
+ ### Generating a Translation (Inference)
316
+
317
+ ```python
318
+ outputs = llm.chat(messages,
319
+ sampling_params=SamplingParams(
320
+ temperature=0, # Greedy decoding (no randomness)
321
+ stop_token_ids=[5], # Stop generation at special token ID (should correspond to <|im_end|>)
322
+ max_tokens=200) # Maximum number of new tokens to generate; increase for longer texts
323
+ )[0].outputs
324
+
325
+ print(outputs[0].text)
326
+ ```
327
+
328
+ ## Prompting Guide
329
+
330
+ The SalamandraTA models were instruction-tuned using a combination of custom prompts and publicly available instruction datasets.
331
+
332
+ - For **sentence-, paragraph- and document-level translation**, we used a single fixed English prompt consistently applied across language pairs. These tasks are the most robust and consistent across the model's output.
333
+ - For **other tasks**, including post-editing, grammar correction, paraphrasing, alternative translations, machine translation evaluation and context-aware translation, we incorporated instruction samples from the [**TowerBlocks** dataset (Alves et al., 2024)]([https://arxiv.org/pdf/2402.17733](https://arxiv.org/pdf/2402.17733)), which provides high-quality, task-diverse instruction tuning data.
334
+ - TowerBlocks includes multiple prompt phrasings per task, often paraphrased or reworded in different ways. As a result, the model has **some tolerance for varied instructions** on these secondary tasks. However, performance may be less consistent than for translation tasks unless prompt phrasing is close to what the model saw during training.
335
+
336
+ <aside>
337
+ 🤖
338
+
339
+ Below we provide examples of recommended prompt structures for each supported task:
340
+
341
+ - **Translation**
342
+
343
+ ```
344
+ Translate the following text from {src} into {tgt}.
345
+ {src}: {context}
346
+ {tgt}:
347
+ ```
348
+
349
+ - **Post-editing**
350
+
351
+ ```
352
+ Please fix any mistakes in the following {source}-{target} machine translation
353
+ or keep it unedited if it's correct.
354
+ Source: {source_sentence}
355
+ MT: {machine_translation}
356
+ Corrected:
357
+ ```
358
+
359
+ - **Context-aware Translation**
360
+
361
+ ```
362
+ What is the {target} translation of the sentence below?
363
+ {sentence}
364
+ Use the following context to help your translation:
365
+ {context}
366
+ Translation:
367
+ ```
368
+
369
+ - **Paraphrasing**
370
+
371
+ ```
372
+ Rewrite the following sentence in {target} without changing its meaning:
373
+ Source: {sentence}
374
+ Paraphrase:
375
+ ```
376
+
377
+ - **Grammar Correction**
378
+
379
+ ```
380
+ Please fix any mistakes in the following {source} sentence or keep it unedited if it's correct.
381
+ Sentence: {sentence}
382
+ Corrected:
383
+ ```
384
+
385
+ - **Named Entity Recognition (NER)**
386
+
387
+ ```
388
+ Analyse the following tokenized text and mark the tokens containing named entities.
389
+ Use the following annotation guidelines with these tags for named entities:
390
+ - ORG (Refers to named groups or organizations)
391
+ - PER (Refers to individual people or named groups of people)
392
+ - LOC (Refers to physical places or natural landmarks)
393
+ - MISC (Refers to entities that don't fit into standard categories).
394
+ Prepend B- to the first token of a given entity and I- to the remaining ones if they exist.
395
+ If a token is not a named entity, label it as O.
396
+ Input: {list of words in a sentence}
397
+ Marked:
398
+ ```
399
+
400
+ - **Machine Translation Evaluation**
401
+
402
+ ```
403
+ Source: {sentence}
404
+ Pick the best English translation from the following pool of candidates:
405
+ 1. {translation_1}
406
+ 2. {translation_2}
407
+ 3. {translation_3}
408
+ 4. {translation_4}
409
+ Choose the translation that best conveys the meaning of the original source by indicating its corresponding number.
410
+ ```
411
+
412
+ </aside>
413
+
414
+ ## Multi-turn Prompts
415
+
416
+ Some tasks supported by the SalamandraTA models, such as Alternative Translations, require multi-turn interactions. These are scenarios where the model is prompted more than once in a conversation-like structure, and each prompt depends on the model’s previous response.
417
+
418
+ Unlike single-shot tasks, multi-turn interactions must be handled programmatically or within a notebook environment, where you can:
419
+
420
+ 1. Send an initial prompt,
421
+ 2. Capture the model’s response,
422
+ 3. Send a second prompt that builds on that response,
423
+ 4. Repeat as needed.
424
+
425
+ This conversational style mirrors the format used during instruction tuning and is important for eliciting coherent, contextual follow-up behavior.
426
+
427
+ ### Load the Model and Tokenizer
428
+
429
+ In order to interact with the model in this way, you should begin by loading the model and tokenizer as in the Quick Start Guide above. Then follow the following steps:
430
+
431
+ ### Define a Chat Helper Function
432
+
433
+ ```python
434
+ def chat(messages, max_new_tokens=200):
435
+ # Convert the message list into a ChatML-style prompt
436
+ # increase max_new_tokens if dealing with longer (paragraph/doc-level) inputs.
437
+ prompt = tokenizer.apply_chat_template(
438
+ messages,
439
+ tokenize=False,
440
+ add_generation_prompt=True
441
+ )
442
+
443
+ # Tokenize the prompt
444
+ inputs = tokenizer.encode(prompt, return_tensors="pt", add_special_tokens=False).to(model.device)
445
+ input_len = inputs.shape[1]
446
+
447
+ # Generate a response using greedy decoding and ChatML-specific stop token
448
+ outputs = model.generate(
449
+ input_ids=inputs,
450
+ max_new_tokens=max_new_tokens,
451
+ pad_token_id=tokenizer.eos_token_id,
452
+ eos_token_id=tokenizer.convert_tokens_to_ids("<|im_end|>")
453
+ )
454
+
455
+ # Return just the newly generated text, skipping special tokens
456
+ return tokenizer.decode(outputs[0, input_len:], skip_special_tokens=True)
457
+
458
+ ```
459
+
460
+ ### Example: Alternative Translations
461
+
462
+ ```python
463
+ # First user message: Request a Catalan translation
464
+ messages = [
465
+ {
466
+ "role": "user",
467
+ "content": 'Given the English sentence "Nothing is achieved without effort.", generate a translation in Catalan.'
468
+ }
469
+ ]
470
+
471
+ # Generate and print the first response
472
+ response_1 = chat(messages)
473
+ print("Response 1:", response_1)
474
+ #Response 1: Translation in Catalan as listed:
475
+ #Res s'aconsegueix sense esforç.
476
+ ```
477
+
478
+ ```python
479
+ # Add model's first reply to the chat history
480
+ messages.append({"role": "assistant", "content": response_1})
481
+
482
+ # Add a second user message requesting an alternative translation
483
+ messages.append({
484
+ "role": "user",
485
+ "content": 'That was a useful translation. For a broader understanding, please provide one additional translation of the English phrase "Nothing is achieved without effort." into Catalan.'
486
+ })
487
+
488
+ # Generate and print the second response
489
+ response_2 = chat(messages)
490
+ print("Response 2:", response_2)
491
+ #Response 2: Res s'aconsegueix sense treballar.
492
+ ```
493
+
494
+ ### Notes on multi-turn interactions
495
+
496
+ This structure can be extended to more than two turns by continuing to append `{"role": "assistant", "content": ...}` and `{"role": "user", "content": ...}` objects to the `messages` list. It can also be used with other tasks - for example, in Machine Translation Evaluation, you could follow up a request for the best translation with a request for the worst.
497
+
498
+ ## Decoding Strategies
499
+
500
+ There are different decoding strategies that can be used with SalamandraTA models for generating translations. The strategy you choose can affect the fluency, accuracy, and consistency of translations or other task outputs.
501
+
502
+ For most use cases, we recommend one of the following:
503
+
504
+ ### **Greedy Decoding** (Default)
505
+
506
+ ---
507
+
508
+ Greedy decoding selects the most likely next token at each step, producing fast and predictable outputs. It is well-suited for most translation tasks where consistency and speed are priorities.
509
+
510
+ - **Use when**: You want reliable, fast inference translations — ideal for most MT and post-editing tasks.
511
+
512
+ ```python
513
+ outputs = model.generate(
514
+ input_ids=inputs.to(model.device),
515
+ max_new_tokens=200,
516
+ num_beams=1, # 1 = greedy decoding
517
+ pad_token_id=tokenizer.eos_token_id
518
+ )
519
+ ```
520
+
521
+ ### **Beam Search**
522
+
523
+ Beam search keeps multiple candidate sequences at each step and chooses the most probable overall sequence after considering these options. This can improve fluency and quality, especially for longer or more complex text, but requires more computational resources and may sometimes produce less consistent end tokens.
524
+
525
+ - **Use when**: You want more polished outputs, are working with longer paragraphs, or are post-selecting among alternatives.
526
+
527
+ ```python
528
+
529
+ outputs = model.generate(
530
+ input_ids=inputs.to(model.device),
531
+ max_new_tokens=200,
532
+ num_beams=5, # > = greedy decoding, generally 5 beams is a good balance between quality and cost
533
+ pad_token_id=tokenizer.eos_token_id
534
+ )
535
+ ```
536
+
537
+ ### **Important Note on End Tokens**
538
+
539
+ The instruction-tuned SalamandraTA models are designed to end outputs with `<|im_end|>`.
540
+
541
+ Greedy decoding reliably respects this. Beam search sometimes prefers `</s>`, depending on how likely `<|im_end|>` is under the beam hypotheses.
542
+
543
+ If needed, set the following to ensure clean stopping behavior:
544
+
545
+ ```python
546
+ stop_sequence = '<|im_end|>'
547
+ eos_tokens = [
548
+ tokenizer.eos_token_id,
549
+ tokenizer.convert_tokens_to_ids(stop_sequence),
550
+ ]
551
+ ```
552
+
553
+ In the generation, it can then be applied as in the following:
554
+
555
+ ```python
556
+ outputs = model.generate(
557
+ input_ids=inputs.to(model.device),
558
+ max_new_tokens=4000,
559
+ early_stopping=True,
560
+ eos_token_id=eos_tokens,
561
+ pad_token_id=tokenizer.eos_token_id,
562
+ num_beams=5
563
+ )
564
+ ```
565
+
566
+ ### Diverse Beam Search
567
+
568
+ Diverse beam search is a variation of beam search that encourages variety among the translation candidates. Instead of just finding the most probable sequences, it aims to find a set of high-probability sequences that are also different from one another. This is achieved by penalizing hypotheses that are too similar to others already in the beam.
569
+
570
+ - **Use when:** You want to generate multiple, distinct translation options for a single source sentence. This is useful for tasks like providing alternative translations or for creating a richer set of candidates for a subsequent quality-aware decoding steps.
571
+
572
+ ```python
573
+ # Use num_beam_groups and diversity_penalty to enable diverse beam search
574
+ # This will generate 5 beams, divided into 5 groups (so each group is independent)
575
+ # The diversity penalty discourages beams within a group from being too similar.
576
+
577
+ outputs = model.generate(
578
+ input_ids=inputs.to(model.device),
579
+ max_new_tokens=200,
580
+ num_beams=5,
581
+ num_beam_groups=5,
582
+ diversity_penalty=1.0,
583
+ pad_token_id=tokenizer.eos_token_id
584
+ )
585
+ ```
586
+
587
+ ## **Quality-Aware Decoding Strategies**
588
+
589
+ While greedy and beam search are powerful, they prioritize statistical likelihood (what the model thinks is the most probable translation) over actual translation quality. This can sometimes lead to the "beam search curse," where translations with the highest probability are not actually the best in terms of quality, sometimes resulting in unnatural text. Quality-aware strategies address this by incorporating a more direct sense of "goodness" into the decoding process. For using quality-aware decoding strategies with SalamandraTA we will need to install two libraries; `mbrs` and `comet`.
590
+
591
+ ```python
592
+ pip install mbrs
593
+ pip install unbabel-comet
594
+ ```
595
+
596
+ Then, we will need a set of candidate translations, we will be using diverse beam search for generating a set of hypothesis. Traditional beam search often generates very similar sequences across different beams. Diverse beam search addresses this by penalizing beams that generate tokens already chosen by other beams in the same time step.
597
+
598
+ ```python
599
+ sentence = "Ayer se fue, tomó sus cosas y se puso a navegar"
600
+ text = (
601
+ f"Translate the following text from {source} into {target}.\n"
602
+ f"{source}: {sentence}\n"
603
+ f"{target}:"
604
+ )
605
+ message = [{"role": "user", "content": text}]
606
+ prompt = tokenizer.apply_chat_template(message, tokenize=False, add_generation_prompt=True)
607
+ inputs = tokenizer.encode(prompt, add_special_tokens=False,return_tensors="pt")
608
+ input_length = inputs.shape[1] # Used to trim the prompt portion from the output
609
+ eos_tokens = [ tokenizer.eos_token_id, tokenizer.convert_tokens_to_ids("<|im_end|>") ]
610
+
611
+ # We will generate 20 candidate translations
612
+ num_hypotheses = 20
613
+ outputs = model.generate(
614
+ input_ids=inputs.to(model.device),
615
+ max_new_tokens=200,
616
+ num_beams=num_hypotheses,
617
+ num_return_sequences=num_hypotheses,
618
+ num_beam_groups=5,
619
+ diversity_penalty=1.0,
620
+ pad_token_id=tokenizer.eos_token_id,
621
+ eos_token_id=tokenizer.convert_tokens_to_ids("<|im_end|>")
622
+ )
623
+
624
+ # Decode all hypotheses into a list of strings
625
+ hypotheses = [ tokenizer.decode(output[input_length:], skip_special_tokens=True).strip().replace('\n', '') for output in outputs]
626
+ ```
627
+
628
+ ### Tuned Re-ranking
629
+
630
+ Tuned re-ranking is a two-step process:
631
+
632
+ 1. **Generation:** First, use a decoding method like beam search or diverse beam search to generate a list of multiple translation candidates (an "N-best list").
633
+ 2. **Re-ranking:** Next, use a second, specialized model—a "re-ranker"—to score each candidate in the N-best list. This re-ranker is often a Quality Estimation (QE) model trained specifically to predict the quality of a translation without needing a human reference. The translation with the highest quality score is then selected as the final output.
634
+
635
+ Use when: You want to achieve the highest possible translation quality. By using a dedicated QE model for the final selection, you can often find a better translation in the N-best list than the main model would have chosen based on probability alone.
636
+
637
+ ```python
638
+ from mbrs.metrics import MetricCOMETkiwi
639
+ from mbrs.decoders import DecoderRerank
640
+
641
+ # 1. Initialize the quality metric you want to use for re-ranking.
642
+ # Here, we use COMET-kiwi, a state-of-the-art metric for quality estimation
643
+ metric_cfg = MetricCOMETkiwi.Config(model="Unbabel/wmt22-cometkiwi-da")
644
+ metric = MetricCOMETkiwi(metric_cfg)
645
+
646
+ # 2. Initialize the re-rank decoder.
647
+ decoder_cfg = DecoderRerank.Config()       
648
+ decoder = DecoderRerank(decoder_cfg, metric)
649
+
650
+ # 3. Decode! The 'decode' method takes your list of hypotheses
651
+ # and re-ranks them according to the selected metric
652
+ result = decoder.decode(hypotheses, source=sentence, nbest=1)
653
+ best_hyp = result.sentence[0]
654
+
655
+ # Print the result selected by Comet-kiwi re-ranking
656
+ print(f"Selected sentence: {best_hyp}")
657
+ ```
658
+
659
+ ### Minimum Bayes Risk (MBR) Decoding
660
+
661
+ Minimum Bayes Risk (MBR) decoding is a powerful alternative that directly optimizes for output quality. Instead of selecting the single most probable hypothesis (as in standard beam search), MBR selects the hypothesis that is most similar, on average, to all other plausible hypotheses.
662
+
663
+ The core idea is to find the candidate translation that has the highest *expected utility* (i.e., the highest average quality score) when compared against a set of other high-quality potential translations, known as "pseudo-references". This approach is effective at avoiding the common problems of standard decoding by favoring consensus and quality over raw probability.
664
+
665
+ ```python
666
+ from mbrs.metrics import MetricCOMET
667
+ from mbrs.decoders import DecoderMBR
668
+
669
+ # 1. Initialize the quality metric you want to use for the utility function.
670
+ # Here, we use COMET, a state-of-the-art metric for neural based-translation
671
+ # quality estimation
672
+ metric_cfg = MetricCOMET.Config(model="Unbabel/wmt22-comet-da")
673
+ metric = MetricCOMET(metric_cfg)
674
+
675
+ # 2. Initialize the MBR decoder.
676
+ decoder_cfg = DecoderMBR.Config()
677
+ decoder = DecoderMBR(decoder_cfg, metric)
678
+
679
+ # 3. Decode! The 'decode' method takes your list of hypotheses and also uses
680
+ # them as the pseudo-references to calculate the expected utility scores.
681
+ result = decoder.decode(hypotheses,hypotheses, source=sentence, nbest=1)
682
+ best_hyp = result.sentence[0]
683
+
684
+ # Print the result selected by MBR decoding
685
+ print(f"Selected sentence: {best_hyp}")
686
+ ```
687
+
688
+ ## **Compatibility Wrapper**
689
+
690
+ In order to integrate SalamandraTA as a drop-in replacement for translation services such as Google Translate or DeepL you can use the wrapper provided at [**https://github.com/langtech-bsc/mt-wrapper**](https://github.com/langtech-bsc/mt-wrapper). This service accepts incoming requests in Google Translate or DeepL format and translates them to appropriately formatted requests to a SalamandraTA endpoint.
691
+
692
+ The wrapper service can be deployed locally or on any hosting platform with minimal resource requirements.