File size: 16,754 Bytes
8768805 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 | ---
license: other
base_model:
- google/gemma-3-270m-it
language: [afr, amh, bam, ewe, fon, ful, gpe, hau, ibo, kik, kin, kon, lin, lug, luo, mlg, nde, nso, nya, orm, pcm, run, sna, som, sot, ssw, swh, tir, tsn, tso, tum, twi, wes, wol, xho, yor, zul, en]
pipeline_tag: text-generation
tags: [african-languages, code-switching, idioms, gemma3]
---
**License: free for commercial and non-commercial use, with attribution. If you use this model, its outputs, or anything derived from it in a product, service, paper or dataset, credit "AletheiaAING" (https://huggingface.co/AletheiaAING) and keep this notice. This model is derived from Google Gemma, so the Gemma Terms of Use also apply.**
# csw (301M)
A small model (301M parameters, 1.2 GB) that code-switches and rewrites text in lively, idiom-rich style in 37 African languages. It also translates from English into those languages. Its bigger relatives are `BeardedMonster/gemma-3-1b-csw-best` and the CPU-friendly `BeardedMonster/gemma-3-0.8b-csw`.
## What it does
| Task | What you give it | What you get | Prompt |
|---|---|---|---|
| `eng_m` | English text | translation into the base language | `Translate the text to Yoruba: TEXT` (language **name**) |
| `eng_hm` | English text | code-switched text | `<hm> <yor>+<eng>: TEXT` |
| `m_hm` | text in the base language | code-switched text | `<hm> <yor>+<eng>: TEXT` |
| `eng_ood` | English text | idiom-rich informal text | `<ood> <yor>: TEXT` |
| `m_ood` | text in the base language | idiom-rich informal text | `<ood> <yor>: TEXT` |
| `hm_ood` | code-switched text | idiom-rich text that keeps the switching | `<ood> <yor>+<eng>: TEXT` |
- **`eng_m`** is plain translation from English, with no mixing.
- **`hm`** is code-switching: two languages mixed the way people talk, for example Yoruba with English words in the middle of a sentence.
- **`ood`** is an idiom-rich rewrite: lively, everyday language full of idiomatic expressions, like a chatty native speaker.
`eng_` means the input is English, `m_` means it is already in the base language, and `hm_ood` means the input is already code-switched and you want the idiom-rich version.
## What you can use it for
- **Chat and instruction data.** Take English or single-language instruction data and turn the user queries, or the assistant replies, into code-switched versions (`eng_hm`, `m_hm`). This helps chat models cope with how people really type to them, mixing languages in one message.
- **Speech data (ASR and TTS).** Generate code-switched sentences to build reading scripts for recording, text for language-model training, and word lists with the switched phrases. Use real speakers for the audio, and have a native speaker check the text first.
- **Testing and stress-testing.** Make mixed-language inputs to check how a chatbot, translation system, language-ID tool or sentiment/NER model copes with them.
- **Language-ID and code-switch detection.** The `<dev>` block marks the switched phrases, so you get labelled spans for training or evaluating detectors.
- **Natural-sounding copy and dialogue.** Rewrite plain text into idiomatic, conversational style (`ood`) for stories, game dialogue, social posts or ad copy, then review it with a native speaker.
- **Language learning.** Show learners how speakers mix languages and which sayings they use.
- **More training data for your own models.** Generate many variants per prompt (sampling several outputs per prompt, or MBR to pick the best) and filter them.
Everything the model writes is machine-generated, so filter it and have it reviewed before you rely on it.
## Quick start
Send a single user turn and no system prompt (`tokenizer.apply_chat_template` does this for you).
- Translation (`eng_m`) is the only task that uses the language **name**: `Translate the text to Yoruba: TEXT`. The names are in the last column of the language table.
- Every other task uses the three-letter **code** in angle brackets: `<hm> <yor>+<eng>: TEXT` or `<ood> <yor>: TEXT`.
- There are two spaces after every colon.
- `<hm>` prompts and `hm_ood` need a switch language from the table. Other pairs were not trained.
- Translation answers start with the language code (`<yor>`). Other tasks answer `<yor><eng><dev>device one | device two</dev> text`, where the `<dev>` block lists the switched phrases or idioms. If that structure is missing, sample again.
## Code
```python
# pip install torch transformers
import random, re, sys, torch
from transformers import AutoModelForCausalLM, AutoTokenizer
NAMES = {'yor': 'Yoruba', 'hau': 'Hausa', 'ibo': 'Igbo', 'pcm': 'Pidgin', 'twi': 'Twi', 'ewe': 'Ewe', 'fon': 'Fon', 'wol': 'Wolof', 'swh': 'Swahili', 'kin': 'Kinyarwanda', 'som': 'Somali', 'orm': 'Oromo', 'amh': 'Amharic', 'tir': 'Tigrinya', 'lug': 'Luganda', 'lin': 'Lingala', 'zul': 'Zulu', 'xho': 'Xhosa', 'afr': 'Afrikaans', 'sna': 'Shona', 'nya': 'Chichewa', 'sot': 'Sesotho', 'tsn': 'Setswana', 'mlg': 'Malagasy', 'tum': 'Tumbuka', 'run': 'Kirundi', 'tso': 'Tsonga', 'nso': 'Sepedi', 'ssw': 'Swati', 'nde': 'North Ndebele', 'kik': 'Kikuyu', 'luo': 'Luo', 'bam': 'Bambara', 'kon': 'Kongo', 'ful': 'Fulah', 'wes': 'Cameroon Pidgin', 'gpe': 'Ghanaian Pidgin'} # base language code -> name used in the TRANSLATION prompt (not the tags)
# switch languages the model was trained with, per base language (anything else is out of distribution)
SWITCH = {'yor': ['eng', 'pcm'], 'hau': ['eng', 'ara'], 'ibo': ['eng', 'pcm'], 'pcm': ['yor', 'ibo', 'hau'], 'twi': ['eng', 'gpe'], 'ewe': ['fra', 'eng'], 'fon': ['fra', 'yor'], 'kin': ['fra', 'eng', 'swh'], 'sna': ['eng', 'nde'], 'zul': ['eng', 'afr'], 'xho': ['eng', 'afr'], 'swh': ['eng', 'ara', 'sheng'], 'orm': ['amh', 'eng'], 'som': ['ara', 'eng', 'ita', 'amh'], 'wol': ['fra', 'ara'], 'tsn': ['eng', 'afr'], 'nya': ['eng', 'tum'], 'afr': ['eng', 'zul'], 'sot': ['eng', 'afr'], 'lin': ['fra', 'kon'], 'run': ['fra', 'swh'], 'bam': ['fra', 'wol'], 'tum': ['eng', 'nya'], 'tso': ['eng', 'zul'], 'nso': ['eng', 'afr'], 'lug': ['eng', 'swh'], 'kik': ['eng', 'swh'], 'luo': ['eng', 'swh'], 'ssw': ['eng', 'zul'], 'nde': ['eng', 'sna'], 'kon': ['fra', 'lin'], 'ful': ['fra', 'eng'], 'mlg': ['fra', 'eng'], 'amh': ['eng', 'ara'], 'tir': ['amh', 'eng'], 'gpe': ['twi', 'ewe', 'gaa'], 'wes': ['fra', 'ewo', 'dua']}
TASKS = ("eng_m", "eng_hm", "m_hm", "eng_ood", "m_ood", "hm_ood")
def build_prompt(task, base, text, switch=None):
"""text = English (eng_*), base-language text (m_*) or code-switched text (hm_ood). Two spaces after every colon."""
if task == "eng_m": # translation: the language NAME, not the code
return f"Translate the text to {NAMES[base]}: {text}"
if task in ("eng_hm", "m_hm"):
switch = switch or random.choice(SWITCH[base])
return f"<hm> <{base}>+<{switch}>: {text}"
if task in ("eng_ood", "m_ood"):
return f"<ood> <{base}>: {text}"
if task == "hm_ood":
if switch is None: raise ValueError("hm_ood needs the switch language of the input text")
return f"<ood> <{base}>+<{switch}>: {text}"
raise ValueError(task)
_LANG = re.compile(r"^((?:<(?!dev>)[a-z]{3,5}>)+)"); _DEV = re.compile(r"<dev>(.*?)</dev>", re.S)
def parse(task, completion):
"""eng_m: 'yor <text>'. Others: '<yor><eng><dev>device one | device two</dev> <text>'."""
c = completion.strip()
if task == "eng_m":
m = re.match(r"^([a-z]{3,5}) (.*)$", c, re.S)
return {"ok": bool(m), "tags": [m.group(1)] if m else [], "devices": [], "text": m.group(2).strip() if m else c}
t = _LANG.match(c)
if not t: return {"ok": False, "tags": [], "devices": [], "text": c}
rest = c[t.end():].lstrip(); d = _DEV.match(rest)
if not d: return {"ok": False, "tags": re.findall(r"<([a-z]{3,5})>", t.group(1)), "devices": [], "text": rest}
text = rest[d.end():].strip()
return {"ok": bool(text), "tags": re.findall(r"<([a-z]{3,5})>", t.group(1)), "devices": [x.strip() for x in d.group(1).split("|") if x.strip()], "text": text}
def load(path):
tok = AutoTokenizer.from_pretrained(path); model = AutoModelForCausalLM.from_pretrained(path, dtype=torch.bfloat16).eval()
return tok, model.to("cuda" if torch.cuda.is_available() else "cpu")
def generate(tok, model, prompt, sample=False, max_new=700):
ids = tok(f"<bos><start_of_turn>user\n{prompt}<end_of_turn>\n<start_of_turn>model\n", add_special_tokens=False, return_tensors="pt").input_ids.to(model.device)
stop = [tok.convert_tokens_to_ids("<end_of_turn>"), tok.eos_token_id]
kw = dict(do_sample=True, temperature=0.7, top_p=0.95) if sample else dict(do_sample=False) # greedy is what all reported numbers use
with torch.no_grad(): out = model.generate(ids, max_new_tokens=max_new, eos_token_id=stop, pad_token_id=tok.pad_token_id or 0, **kw)
return tok.decode(out[0][ids.shape[1]:], skip_special_tokens=False).replace("<end_of_turn>", "").replace("<eos>", "").replace("<pad>", "").strip()
tok, model = load("BeardedMonster/csw # or a local download of this repository")
en = "My brother told me that the meeting about the new school fees will start at ten tomorrow, so we must leave early."
print(parse("eng_m", generate(tok, model, build_prompt("eng_m", "yor", en)))["text"]) # translation
print(parse("eng_hm", generate(tok, model, build_prompt("eng_hm", "yor", en, "eng")))["text"]) # code-switching
print(parse("eng_ood", generate(tok, model, build_prompt("eng_ood", "yor", en)))["text"]) # idiom-rich rewrite
```
Greedy decoding is what all reported numbers use. For several candidates use temperature 0.7, top-p 0.95; sampling several candidates does not raise chrF++ much on its own.
## Performance
Held-out test set, 6,230 items in 34 languages, greedy decoding, chrF++ averaged over languages. The references are rewrites written by language models, so the score measures closeness to that style, not human ratings.
| Task | chrF++ |
|---|---|
| eng_hm | 50.05 |
| m_hm | 55.58 |
| eng_ood | 35.69 |
| m_ood | 40.49 |
| hm_ood | 37.96 |
About 95% of code-switching outputs have the required format.
## Supported languages and switch languages
| Language | Code used in prompts | Switch languages (trained pairs) | Example prompt (code-switching) | Translation prompt (name, not code) |
|---|---|---|---|---|
| Afrikaans | `afr` | English `eng`, Zulu `zul` | `<hm> <afr>+<eng>: TEXT` | `Translate the text to Afrikaans: TEXT` |
| Amharic | `amh` | English `eng`, Arabic `ara` | `<hm> <amh>+<eng>: TEXT` | `Translate the text to Amharic: TEXT` |
| Bambara | `bam` | French `fra`, Wolof `wol` | `<hm> <bam>+<fra>: TEXT` | `Translate the text to Bambara: TEXT` |
| Cameroonian Pidgin | `wes` | French `fra`, Ewondo `ewo`, Duala `dua` | `<hm> <wes>+<fra>: TEXT` | `Translate the text to Cameroon Pidgin: TEXT` |
| Chichewa | `nya` | English `eng`, Tumbuka `tum` | `<hm> <nya>+<eng>: TEXT` | `Translate the text to Chichewa: TEXT` |
| Ewe | `ewe` | French `fra`, English `eng` | `<hm> <ewe>+<fra>: TEXT` | `Translate the text to Ewe: TEXT` |
| Fon | `fon` | French `fra`, Yoruba `yor` | `<hm> <fon>+<fra>: TEXT` | `Translate the text to Fon: TEXT` |
| Fulah | `ful` | French `fra`, English `eng` | `<hm> <ful>+<fra>: TEXT` | `Translate the text to Fulah: TEXT` |
| Ghanaian Pidgin | `gpe` | Twi `twi`, Ewe `ewe`, Ga `gaa` | `<hm> <gpe>+<twi>: TEXT` | `Translate the text to Ghanaian Pidgin: TEXT` |
| Hausa | `hau` | English `eng`, Arabic `ara` | `<hm> <hau>+<eng>: TEXT` | `Translate the text to Hausa: TEXT` |
| Igbo | `ibo` | English `eng`, Nigerian Pidgin `pcm` | `<hm> <ibo>+<eng>: TEXT` | `Translate the text to Igbo: TEXT` |
| Kikuyu | `kik` | English `eng`, Swahili `swh` | `<hm> <kik>+<eng>: TEXT` | `Translate the text to Kikuyu: TEXT` |
| Kinyarwanda | `kin` | French `fra`, English `eng`, Swahili `swh` | `<hm> <kin>+<fra>: TEXT` | `Translate the text to Kinyarwanda: TEXT` |
| Kirundi | `run` | French `fra`, Swahili `swh` | `<hm> <run>+<fra>: TEXT` | `Translate the text to Kirundi: TEXT` |
| Kongo | `kon` | French `fra`, Lingala `lin` | `<hm> <kon>+<fra>: TEXT` | `Translate the text to Kongo: TEXT` |
| Lingala | `lin` | French `fra`, Kongo `kon` | `<hm> <lin>+<fra>: TEXT` | `Translate the text to Lingala: TEXT` |
| Luganda | `lug` | English `eng`, Swahili `swh` | `<hm> <lug>+<eng>: TEXT` | `Translate the text to Luganda: TEXT` |
| Luo | `luo` | English `eng`, Swahili `swh` | `<hm> <luo>+<eng>: TEXT` | `Translate the text to Luo: TEXT` |
| Malagasy | `mlg` | French `fra`, English `eng` | `<hm> <mlg>+<fra>: TEXT` | `Translate the text to Malagasy: TEXT` |
| Nigerian Pidgin | `pcm` | Yoruba `yor`, Igbo `ibo`, Hausa `hau` | `<hm> <pcm>+<yor>: TEXT` | `Translate the text to Pidgin: TEXT` |
| North Ndebele | `nde` | English `eng`, Shona `sna` | `<hm> <nde>+<eng>: TEXT` | `Translate the text to North Ndebele: TEXT` |
| Oromo | `orm` | Amharic `amh`, English `eng` | `<hm> <orm>+<amh>: TEXT` | `Translate the text to Oromo: TEXT` |
| Sepedi | `nso` | English `eng`, Afrikaans `afr` | `<hm> <nso>+<eng>: TEXT` | `Translate the text to Sepedi: TEXT` |
| Sesotho | `sot` | English `eng`, Afrikaans `afr` | `<hm> <sot>+<eng>: TEXT` | `Translate the text to Sesotho: TEXT` |
| Setswana | `tsn` | English `eng`, Afrikaans `afr` | `<hm> <tsn>+<eng>: TEXT` | `Translate the text to Setswana: TEXT` |
| Shona | `sna` | English `eng`, North Ndebele `nde` | `<hm> <sna>+<eng>: TEXT` | `Translate the text to Shona: TEXT` |
| Somali | `som` | Arabic `ara`, English `eng`, Italian `ita`, Amharic `amh` | `<hm> <som>+<ara>: TEXT` | `Translate the text to Somali: TEXT` |
| Swahili | `swh` | English `eng`, Arabic `ara`, Sheng `sheng` | `<hm> <swh>+<eng>: TEXT` | `Translate the text to Swahili: TEXT` |
| Swati | `ssw` | English `eng`, Zulu `zul` | `<hm> <ssw>+<eng>: TEXT` | `Translate the text to Swati: TEXT` |
| Tigrinya | `tir` | Amharic `amh`, English `eng` | `<hm> <tir>+<amh>: TEXT` | `Translate the text to Tigrinya: TEXT` |
| Tsonga | `tso` | English `eng`, Zulu `zul` | `<hm> <tso>+<eng>: TEXT` | `Translate the text to Tsonga: TEXT` |
| Tumbuka | `tum` | English `eng`, Chichewa `nya` | `<hm> <tum>+<eng>: TEXT` | `Translate the text to Tumbuka: TEXT` |
| Twi | `twi` | English `eng`, Ghanaian Pidgin `gpe` | `<hm> <twi>+<eng>: TEXT` | `Translate the text to Twi: TEXT` |
| Wolof | `wol` | French `fra`, Arabic `ara` | `<hm> <wol>+<fra>: TEXT` | `Translate the text to Wolof: TEXT` |
| Xhosa | `xho` | English `eng`, Afrikaans `afr` | `<hm> <xho>+<eng>: TEXT` | `Translate the text to Xhosa: TEXT` |
| Yoruba | `yor` | English `eng`, Nigerian Pidgin `pcm` | `<hm> <yor>+<eng>: TEXT` | `Translate the text to Yoruba: TEXT` |
| Zulu | `zul` | English `eng`, Afrikaans `afr` | `<hm> <zul>+<eng>: TEXT` | `Translate the text to Zulu: TEXT` |
## How it was trained
1. Start from Gemma-3-270M-it, trained for English-to-African translation, with language tags added and extra layers inserted (301M parameters).
2. Supervised fine-tuning on code-switching and idiom-rewriting examples in 37 African languages.
## Benchmark dataset
Our test set for African-language code-switching is public as [African Code-Switch Benchmark](https://huggingface.co/datasets/BeardedMonster/african-code-switch-benchmark). Its `test` split has 11,100 English texts with exactly 300 per language (37 languages), plus 6,230 curated items in 34 languages with references and scores, and a `train` split to build better models. Every row has the prompt, candidate outputs and a cleaned `output` column. It is meant to become the benchmark for measuring progress on African-language code-switching, and we welcome contributions, especially from native speakers.
## Limitations
- The outputs are machine-written and no native speaker has reviewed them. Expect some awkward phrasing, invented idioms or proverbs, wrong tone marks and the odd change of meaning. Have a person check anything that matters.
- Quality depends on the language and the language pair. Low-resource languages are weaker, and the per-language numbers are noisy because some languages have few test items.
- It rewrites, it doesn't translate. It can drop or add content. Pidgin outputs keep a lot of English, because English words are normal in Pidgin.
- Quality was measured with chrF++ and a learned quality score, not with human raters, and there is no extra safety training beyond the base model.
## License
Free for commercial use with attribution to AletheiaAING (see the notice at the top). The model is built on Google Gemma, so the [Gemma Terms of Use](https://ai.google.dev/gemma/terms) and prohibited use policy apply as well.
|