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.

gemma-3-1b-csw-sft

This is the supervised-only version of our 1B code-switching model (full vocabulary). Its chrF++ is about the same as the best model's, but it breaks the output format more often (valid on 92% of code-switching outputs against 97% or more). For most uses pick gemma-3-1b-csw-best.

What it does

It does two things with text, in 37 African languages:

  • Code-switching (hm): the text mixes two languages the way people talk, for example Yoruba with English words in the middle of a sentence ("Ma explain fรบn แบน bรญ a แนฃe ล„ generate funds"). You pick the base language and the language to mix in.
  • Idiom-rich rewriting (ood): the text is rewritten in lively, everyday language full of idiomatic expressions (including sayings and comparisons) just like a native speaker would.
Task What you give it What you get Prompt (Yoruba as an example)
eng_hm English text the same meaning in the base language with phrases of the switch language mixed in <hm> <yor>+<eng>: I will explain the method we use.
m_hm text in the base language the same text, code-switched <hm> <yor>+<eng>: รˆmi yรณรฒ แนฃร lร yรฉ แปฬ€nร  tรญ a ล„ gbร .
eng_ood English text a lively, idiom-rich rewrite in the base language <ood> <yor>: I will explain the method we use.
m_ood text in the base language an idiom-rich rewrite in the same language <ood> <yor>: รˆmi yรณรฒ แนฃร lร yรฉ แปฬ€nร  tรญ a ล„ gbร .
hm_ood an already code-switched text an idiom-rich rewrite that keeps the switching <ood> <yor>+<eng>: รˆmi yรณรฒ explain แปฬ€nร  tรญ a ล„ gbร .

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 of it. This model does not do plain translation; use a translation model for that.

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 one user message and nothing else, no system prompt. The message is <task> <base>[+<switch>]: TEXT:

  • <hm> asks for code-switching and <ood> for the idiom-rich rewrite.
  • Languages are written as their three-letter code in angle brackets, like <yor>, never the name.
  • There are two spaces after the colon.
  • <hm> prompts and hm_ood need a switch language, and it must be one of the pairs in the language table below. For <ood> on plain text, leave it out.
  • Write the tags as plain text exactly as shown and use the tokenizer in this repository.

The answer always looks like <base>[<switch>]<dev>device one | device two</dev> text. The <dev> block lists the switched phrases or idioms the model used, and the text follows. If the <dev> block is missing, treat the output as invalid and sample again. For example:

<yor><eng><dev>explain | generate funds | members</dev> Ma explain fรบn แบน bรญ a แนฃe ล„ generate funds fรบn ร wแปn members wa. ...

A few outputs (prompts are shortened):

Prompt Output
<hm> <pcm>+<hau>: You are informing me that your maize farm is unsuccessful and the crops are not growing. ... <pcm><hau><dev>wallahi | kai | gaskiya | insha Allah</dev> You dey tell me say your maize farm no work and the crops no dey grow, wallahi. You talk say you don dey pray and wait every day, but you no do any manual labor, kai! ...
<hm> <yor>+<eng>: I will explain the method we use to generate funds for our members. ... <yor><eng><dev>explain | generate funds | members | contribute small amount daily | ...</dev> Ma explain fรบn แบน bรญ a แนฃe ล„ generate funds fรบn ร wแปn members wa. แบธnรฌ kแปฬ€แปkan ล„ contribute small amount ...
<ood> <pcm>: Some young individuals are easily deceived into giving their remaining funds to fraudulent religious leaders ... <pcm><dev>na wash dem dey wash dem | prayer fit cook rice | money no dey fall from sky like rain</dev> Some young people na wash dem dey wash dem, dem just dey throw their last kobo give fake prophet because dem think say miracle go happen. ...

Some devices are awkward or made up, as in the Pidgin idiom example.

Code

# pip install vllm transformers huggingface_hub
from vllm import LLM, SamplingParams
from transformers import AutoTokenizer
from huggingface_hub import snapshot_download
from csw_helpers import build_prompt, parse          # helper file below (also in this repository)

repo = "BeardedMonster/gemma-3-1b-csw-sft"
path = snapshot_download(repo, allow_patterns=["*.json", "*.model", "*.jinja", "model.safetensors"])   # skips the extra checkpoint folders
tok = AutoTokenizer.from_pretrained(path)
stop = [tok.convert_tokens_to_ids("<end_of_turn>"), tok.eos_token_id]
llm = LLM(model=path, dtype="bfloat16", max_model_len=2048)

def generate(prompts, temperature=0.0, n=1):
    ids = [{"prompt_token_ids": tok(tok.apply_chat_template([{"role": "user", "content": p}], tokenize=False, add_generation_prompt=True), add_special_tokens=False)["input_ids"]} for p in prompts]
    sp = SamplingParams(temperature=temperature, n=n, max_tokens=768, stop_token_ids=stop, skip_special_tokens=False)
    return [[o.text.replace("<end_of_turn>", "").strip() for o in g.outputs] for g in llm.generate(ids, sp)]

prompt = build_prompt("eng_hm", "yor", "I will explain the method we use to generate funds for our members.", "eng")   # build_prompt / parse: see below
print(parse(generate([prompt])[0][0]))

The vLLM path above is the one used for the numbers in this card.

Helper code (prompt builder and parser)

Save as csw_helpers.py. build_prompt checks the language pair against the table above, parse splits an answer into devices and text, and ask calls any OpenAI-compatible server (llama.cpp llama-server, vLLM vllm serve).

"""csw helpers: build a prompt, call a model served by llama.cpp / vLLM (OpenAI-compatible), parse the answer."""
import json, re, urllib.request

# base language -> switch languages the model was trained with (use only these pairs)
ALLOWED_SWITCH = {
    "afr": ["eng"],
    "amh": ["eng"],
    "bam": ["fra"],
    "ewe": ["fra", "eng"],
    "fon": ["fra", "yor"],
    "ful": ["fra", "eng"],
    "gpe": ["twi", "ewe", "gaa"],
    "hau": ["eng", "ara"],
    "ibo": ["eng", "pcm"],
    "kik": ["eng", "swh"],
    "kin": ["fra", "eng", "swh"],
    "kon": ["fra", "lin"],
    "lin": ["fra"],
    "lug": ["eng", "swh"],
    "luo": ["eng", "swh"],
    "mlg": ["fra"],
    "nde": ["eng", "sna"],
    "nso": ["eng"],
    "nya": ["eng", "tum"],
    "orm": ["amh", "eng"],
    "pcm": ["yor", "ibo", "hau"],
    "run": ["fra", "swh"],
    "sna": ["eng"],
    "som": ["ara", "eng"],
    "sot": ["eng", "afr"],
    "ssw": ["eng", "zul"],
    "swh": ["eng", "ara", "sheng"],
    "tir": ["amh", "eng"],
    "tsn": ["eng", "afr"],
    "tso": ["eng", "zul"],
    "tum": ["eng", "nya"],
    "twi": ["eng", "gpe"],
    "wes": ["fra"],
    "wol": ["fra"],
    "xho": ["eng"],
    "yor": ["eng", "pcm"],
    "zul": ["eng"],
}

TASKS = ("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).
    The language is written as its three-letter code in angle brackets; there are TWO spaces after the colon."""
    if base not in ALLOWED_SWITCH: raise ValueError(f"unsupported base language {base!r}")
    if task in ("eng_hm", "m_hm", "hm_ood"):
        switch = switch or ALLOWED_SWITCH[base][0]
        if switch not in ALLOWED_SWITCH[base]: raise ValueError(f"{switch!r} is not a trained switch language of {base!r}: {ALLOWED_SWITCH[base]}")
    if task in ("eng_hm", "m_hm"): return f"<hm> <{base}>+<{switch}>:  {text}"
    if task in ("eng_ood", "m_ood"): return f"<ood> <{base}>:  {text}"
    if task == "hm_ood": return f"<ood> <{base}>+<{switch}>:  {text}"
    raise ValueError(task)

_TAGS = re.compile(r"^((?:<(?!/?dev>)[a-z]{3,5}>)+)"); _DEV = re.compile(r"<dev>(.*?)</dev>", re.S)

def parse(completion):
    """'<yor><eng><dev>phrase one | phrase two</dev> text'  ->  {'ok', 'tags', 'devices', 'text'}"""
    c = completion.replace("<end_of_turn>", "").strip(); t = _TAGS.match(c); rest = c[t.end():].lstrip() if t else c; d = _DEV.match(rest)
    text = rest[d.end():].strip() if d else rest
    return {"ok": bool(t and d and text), "tags": re.findall(r"<([a-z]{3,5})>", t.group(1)) if t else [], "devices": [x.strip() for x in d.group(1).split("|") if x.strip()] if d else [], "text": text}

def ask(prompt, url="http://127.0.0.1:8080/v1/chat/completions", temperature=0.0, max_tokens=600):
    body = {"messages": [{"role": "user", "content": prompt}], "temperature": temperature, "max_tokens": max_tokens}
    req = urllib.request.Request(url, json.dumps(body).encode(), {"Content-Type": "application/json"})
    return json.loads(urllib.request.urlopen(req, timeout=600).read())["choices"][0]["message"]["content"]

if __name__ == "__main__":
    out = parse(ask(build_prompt("eng_hm", "yor", "I will explain the method we use to generate funds for our members.", "eng")))
    print(out["ok"], out["tags"], out["devices"]); print(out["text"])

Decoding: greedy or MBR-16

Greedy decoding is the default and what the greedy numbers use. Sampling 16 outputs (temperature 0.8) and keeping the one that agrees most with the others (minimum Bayes risk, chrF++ as the agreement measure) gave +1.17 chrF++ on the full test set (47.83 to 49.00), better on all five tasks, at 16 times the generation cost.

import re
from sacrebleu.metrics import CHRF
chrf = CHRF(word_order=2)

def mbr(prompt, n=16, temperature=0.8):
    outs = [ask(prompt, temperature=temperature) for _ in range(n)]        # ask() from csw_helpers (sampled)
    outs = [o for o in outs if parse(o)["ok"]] or outs
    texts = [parse(o)["text"] for o in outs]
    score = [sum(chrf.sentence_score(t, [u]).score for j, u in enumerate(texts) if j != i) for i, t in enumerate(texts)]
    return outs[max(range(len(outs)), key=score.__getitem__)]

Performance

Held-out test set: 6,230 items in 34 of the 37 languages, scored with chrF++ against one reference, averaged over tasks and languages. The references are rewrites written by language models, so the score tells you how close an output is to that style, not how a person would rate it.

Task Greedy With MBR-16
eng_hm 53.80 n/a
m_hm 59.28 n/a
eng_ood 41.09 n/a
m_ood 44.17 n/a
hm_ood 41.93 n/a
mean 48.05 n/a

Greedy decoding scores 48.05 chrF++ on average. The model produces the required output format on 97 to 100% of prompts.

Supported languages and switch languages

37 base languages. Use the code in the second column, and only the switch languages listed for that language. Other pairs were not trained and come out unnatural.

Language Code used in prompts Switch languages (trained pairs) Example prompt (code-switching)
Afrikaans afr English eng <hm> <afr>+<eng>: TEXT
Amharic amh English eng <hm> <amh>+<eng>: TEXT
Bambara bam French fra <hm> <bam>+<fra>: TEXT
Cameroonian Pidgin wes French fra <hm> <wes>+<fra>: TEXT
Chichewa nya English eng, Tumbuka tum <hm> <nya>+<eng>: TEXT
Ewe ewe French fra, English eng <hm> <ewe>+<fra>: TEXT
Fon fon French fra, Yoruba yor <hm> <fon>+<fra>: TEXT
Fulah ful French fra, English eng <hm> <ful>+<fra>: TEXT
Ghanaian Pidgin gpe Twi twi, Ewe ewe, Ga gaa <hm> <gpe>+<twi>: TEXT
Hausa hau English eng, Arabic ara <hm> <hau>+<eng>: TEXT
Igbo ibo English eng, Nigerian Pidgin pcm <hm> <ibo>+<eng>: TEXT
Kikuyu kik English eng, Swahili swh <hm> <kik>+<eng>: TEXT
Kinyarwanda kin French fra, English eng, Swahili swh <hm> <kin>+<fra>: TEXT
Kirundi run French fra, Swahili swh <hm> <run>+<fra>: TEXT
Kongo kon French fra, Lingala lin <hm> <kon>+<fra>: TEXT
Lingala lin French fra <hm> <lin>+<fra>: TEXT
Luganda lug English eng, Swahili swh <hm> <lug>+<eng>: TEXT
Luo luo English eng, Swahili swh <hm> <luo>+<eng>: TEXT
Malagasy mlg French fra <hm> <mlg>+<fra>: TEXT
Nigerian Pidgin pcm Yoruba yor, Igbo ibo, Hausa hau <hm> <pcm>+<yor>: TEXT
North Ndebele nde English eng, Shona sna <hm> <nde>+<eng>: TEXT
Oromo orm Amharic amh, English eng <hm> <orm>+<amh>: TEXT
Sepedi nso English eng <hm> <nso>+<eng>: TEXT
Sesotho sot English eng, Afrikaans afr <hm> <sot>+<eng>: TEXT
Setswana tsn English eng, Afrikaans afr <hm> <tsn>+<eng>: TEXT
Shona sna English eng <hm> <sna>+<eng>: TEXT
Somali som Arabic ara, English eng <hm> <som>+<ara>: TEXT
Swahili swh English eng, Arabic ara, Sheng sheng <hm> <swh>+<eng>: TEXT
Swati ssw English eng, Zulu zul <hm> <ssw>+<eng>: TEXT
Tigrinya tir Amharic amh, English eng <hm> <tir>+<amh>: TEXT
Tsonga tso English eng, Zulu zul <hm> <tso>+<eng>: TEXT
Tumbuka tum English eng, Chichewa nya <hm> <tum>+<eng>: TEXT
Twi twi English eng, Ghanaian Pidgin gpe <hm> <twi>+<eng>: TEXT
Wolof wol French fra <hm> <wol>+<fra>: TEXT
Xhosa xho English eng <hm> <xho>+<eng>: TEXT
Yoruba yor English eng, Nigerian Pidgin pcm <hm> <yor>+<eng>: TEXT
Zulu zul English eng <hm> <zul>+<eng>: TEXT

How it was trained

  1. Start from Gemma-3-1B-it.
  2. Supervised fine-tuning on code-switching and idiom-rewriting examples in 37 African languages.
  3. Reinforcement learning with a reward that checks the output format, language use and copying of the source, plus a learned quality score.

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.

Other models in this family

Repository What it is
BeardedMonster/gemma-3-0.8b-csw 8-bit GGUF, about 0.82B parameters, runs on CPU
BeardedMonster/gemma-3-1b-csw-best-pruned-fp8 smaller vocabulary, FP8 for vLLM
BeardedMonster/gemma-3-1b-csw-best-pruned smaller vocabulary, bf16
BeardedMonster/gemma-3-1b-csw-best best model, full vocabulary, bf16
BeardedMonster/gemma-3-1b-csw-sft supervised-only model
BeardedMonster/csw 301M version

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.

Downloads last month
22
Safetensors
Model size
1.0B params
Tensor type
F32
ยท
Inference Providers NEW
This model isn't deployed by any Inference Provider. ๐Ÿ™‹ Ask for provider support

Model tree for BeardedMonster/gemma-3-1b-csw-sft

Finetuned
(595)
this model