csw / README.md
BeardedMonster's picture
Copy of AletheiaAING/csw
8768805 verified
|
Raw History Blame Contribute Delete
16.8 kB
metadata
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

# 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. 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 and prohibited use policy apply as well.