/ Модель

Характеристики

Контекст
8 192 токена
Параметры
1,4 млрд
Размер весов
14,7 ГБ
Лицензия
Apache 2.0
Архитектура
lladamoe · MoE
Базовая модель
LLaDA-MoE-7B-A1B-Instruct
Опубликована
29 сен 2026

llada-moe-7b-hindi-cot-translator-dinfer

Генерация текстаТекст → текст3 профессии
18скачиваний за 30 дней0лайковвеса обновлены29 сен 2026

Описание модели

Составлено на русском по карточке модели и метаданным Hugging Face

Дообученная модель LLaDA-MoE переводит отдельные шаги рассуждений с английского на хинди с ускоренным декодированием через dInfer.

Athekunal разработал LLaDA-MoE-7B-A1B Hindi Chain-of-Thought Translator как дообученную модель для перевода отдельных шагов рассуждений с английского на хинди. Это masked diffusion language model с архитектурой MoE на базе inclusionAI/LLaDA-MoE-7B-A1B-Instruct; в README указаны 64 эксперта, 8 активных экспертов на токен и около 7 млрд общих параметров. Метаданные каталога указывают 1,4 млрд параметров, контекст 8192 токена и формат safetensors. Чекпойнт подготовлен для ускоренного декодера dInfer, а веса экспертов заранее объединены в его формат.

Модель обучена на 100 000 фрагментах рассуждений на английском языке из набора english-hindi-reasoning-dataset. Она предназначена для пошагового перевода цепочек рассуждений на хинди; математические выражения, код, числа и имена переменных следует сохранять без изменений. Лицензия — Apache-2.0, унаследованная от базовой модели.

Для длинных текстов README рекомендует сначала разбивать рассуждения на небольшие фрагменты по границам абзацев и предложений. При слишком большом фиксированном поле декодирования модель может дублировать текст. Ускоренное пороговое декодирование dInfer работает быстрее обычной пошаговой выборки, но в приведённой небольшой оценке показало немного более низкое качество; результаты оценки шумные.

Сценарии применения

  • перевод отдельных шагов англоязычной цепочки рассуждений на хинди
  • перевод математических объяснений с сохранением формул и чисел
  • перевод рассуждений с кодом и именами переменных без изменения идентификаторов

Ограничения

Модель обучена переводить отдельные шаги рассуждений, поэтому длинный текст нужно предварительно разбивать на небольшие фрагменты. Слишком большой размер поля декодирования может приводить к повторам, а ускоренное пороговое декодирование в небольшой оценке показало несколько более низкое качество.

Публичные бенчмарки

Результаты из открытых лидербордов в сравнении с лидерами каталога

Публичных оценок пока нет

В подключённых источниках результатов этой модели не нашлось. Отсутствие оценки не значит, что модель хуже: её могли просто не проверять.

Источники: Hugging Face Leaderboards, Hugging Face Eval Results, Open LLM v2, MTEB, timm, Open ASR, EvalPlus, LLM Stats

Для каких профессий подходит3

Разделы каталога профессий, в задачах которых используется эта модель

Все профессии

Карточка модели

README от автора на Hugging Face, как он его опубликовал

Открыть на Hugging Face

LLaDA-MoE-7B-A1B Hindi Chain-of-Thought Translator (dInfer checkpoint)

A LLaDA-MoE-7B-A1B-Instruct masked diffusion LM (MDLM), fine-tuned to translate English chain-of-thought reasoning steps into Hindi, one reasoning step at a time. This is the fused checkpoint for dInfer: the MoE expert weights are pre-fused into dInfer's w1/w2 layout for its threshold-parallel decoder and dual KV-cache, which gives roughly a 30x speed-up over one-token-per-step sampling (see benchmarks below).

  • Base model: inclusionAI/LLaDA-MoE-7B-A1B-Instruct (bidirectional MDLM, 64 experts, 8 active/token, ~1B active / ~7B total parameters)
  • Fine-tuned on: Athekunal/english-hindi-reasoning-dataset (sft config, sft_split), 100,000 chunked English→Hindi reasoning steps, 1 epoch
  • Task: translate one reasoning step at a time — not a whole document in one pass. Math, code, numbers and variable names are expected to be reproduced verbatim.
  • A non-fused checkpoint (plain HF safetensors, no dInfer-specific layout) can be requested if you want to run it through the ordinary dllm MDLM sampler instead of dInfer.

Quickstart: chunk a chain-of-thought and translate it with dInfer

Because this is a step translator, a long chain-of-thought first needs to be split into steps small enough to decode cleanly (the model is bidirectional and decodes into a canvas of fixed length chosen up front — an oversized canvas makes it duplicate or repeat text instead of stopping). The snippet below does both: it chunks a CoT into token-capped, boundary-respecting pieces, then runs them through dInfer's threshold-parallel decoder with a dual KV-cache.

Install dInfer first (see its repo — a plain transformers load of this checkpoint will not work, since its modeling_fused_olmoe.py calls into dInfer/vLLM-specific fused-MoE kernels):

git clone https://github.com/inclusionAI/dInfer.git .dinfer
pip install -e .dinfer  # pulls vllm; pin transformers back afterwards if it upgrades it, e.g. pip install "transformers==4.57.1"

1. Chunk the chain-of-thought

Splits at paragraph breaks first, then sentence ends, then single newlines — never mid-sentence, and never inside a code fence or $...$ / $$...$$ math block (those are masked while splitting). Pieces are balanced so a batch doesn't waste canvas on one long piece next to short ones.

"""Splits a long step into balanced pieces that each fit a token cap, without breaking mid-sentence.

Boundaries are chosen in order of preference: paragraph breaks, sentence ends, then single newlines. Code fences and
`$...$` / `$$...$$` math are masked while splitting so a boundary never lands inside one. Pieces are balanced
(each close to total / n_pieces tokens) so they decode in same-length batches. A single unit longer than the cap
(e.g. a huge code fence with no newlines) stays whole in its own piece.

    pieces, seps = split_text(text, count_tokens, cap=450)
    text == join_pieces(pieces, seps)     # with `seps[0]` the leading and `seps[i]` the gap after piece i-1
"""

import math
import re
from typing import Callable

_PROTECT = re.compile(r"```.*?```|\$\$.*?\$\$|\$[^$\n]+\$", re.DOTALL)
_PARA = re.compile(r"(\n[ \t]*\n\s*)")
_SENT = re.compile(r"((?<=[.!?।])\s+)")
_LINE = re.compile(r"(\n)")


def _units(text: str, count: Callable[[str], int], cap: int) -> list[tuple[str, str]]:
    """Returns [(unit_text, whitespace_after)] where no unit is splittable further within `cap` if avoidable."""
    saved: list[str] = []

    def mask(m: re.Match) -> str:
        saved.append(m.group(0))
        return f"\x00{len(saved) - 1}\x00"

    masked = _PROTECT.sub(mask, text)
    restore = lambda s: re.sub(r"\x00(\d+)\x00", lambda m: saved[int(m.group(1))], s)

    def pairs(parts: list[str]) -> list[tuple[str, str]]:
        # re.split with a capture group alternates text, separator, text, ...
        return [(parts[i], parts[i + 1] if i + 1 < len(parts) else "") for i in range(0, len(parts), 2)]

    out: list[tuple[str, str]] = []
    for para, para_sep in pairs(_PARA.split(masked)):
        if count(restore(para)) <= cap:
            out.append((restore(para), para_sep))
            continue
        sents = pairs(_SENT.split(para))
        for k, (sent, sent_sep) in enumerate(sents):
            sep = sent_sep if k < len(sents) - 1 else para_sep
            if count(restore(sent)) <= cap:
                out.append((restore(sent), sep))
                continue
            lines = pairs(_LINE.split(sent))
            for j, (line, line_sep) in enumerate(lines):
                out.append((restore(line), line_sep if j < len(lines) - 1 else sep))
    return out


def split_text(text: str, count: Callable[[str], int], cap: int) -> tuple[list[str], list[str]]:
    """Returns (pieces, seps): `seps` has len(pieces) + 1 entries: leading whitespace, the gap after each piece
    (the last being trailing whitespace). Every piece is stripped and non-empty."""
    if count(text) <= cap:
        return [text.strip()], [text[: len(text) - len(text.lstrip())], text[len(text.rstrip()) :]]
    # normalise: every unit is (core, whitespace_after); stray whitespace moves into the neighbouring separator
    merged: list[tuple[str, str]] = []
    lead = ""
    for t, sep in _units(text, count, cap):
        core = t.strip()
        pre, post = t[: len(t) - len(t.lstrip())], t[len(t.rstrip()) :] if core else ""
        if not core:
            pre, post = t, ""
        if merged:
            merged[-1] = (merged[-1][0], merged[-1][1] + pre)
        else:
            lead += pre
        if core:
            merged.append((core, post + sep))
        elif merged:
            merged[-1] = (merged[-1][0], merged[-1][1] + sep)
        else:
            lead += sep
    counts = [count(t) for t, _ in merged]
    n = max(1, math.ceil(sum(counts) / cap))
    target = sum(counts) / n
    groups: list[list[int]] = [[]]
    cur = 0
    for i, c in enumerate(counts):
        # start a new piece when adding this unit would overshoot the balanced target more than stopping short
        if groups[-1] and (cur + c > cap or cur + c - target > target - cur):
            groups.append([])
            cur = 0
        groups[-1].append(i)
        cur += c
    pieces, seps = [], [lead]
    for g in groups:
        body = "".join(merged[i][0] + (merged[i][1] if i != g[-1] else "") for i in g)
        pieces.append(body)
        seps.append(merged[g[-1]][1])
    return pieces, seps


def join_pieces(pieces: list[str], seps: list[str]) -> str:
    return seps[0] + "".join(p + s for p, s in zip(pieces, seps[1:]))

Source: chunk_splitter.py in the training repo — copied here verbatim so this card is runnable standalone.

2. Load the model with dInfer and translate

import torch
from transformers import AutoConfig, AutoTokenizer
from vllm import distributed
from vllm.config import ParallelConfig, VllmConfig, set_current_vllm_config
from dinfer import BlockIteratorFactory, IterSmoothWithVicinityCacheDiffusionLLM, KVCacheFactory, ThresholdParallelDecoder
from dinfer.model import LLaDAMoeModelLM

REPO = "Athekunal/llada-moe-7b-hindi-cot-translator-dinfer"
MASK_ID, EOS_ID, BLOCK = 156895, 156892, 64
PROMPT = "<role>SYSTEM</role>detailed thinking off<|role_end|><role>HUMAN</role>{}<|role_end|><role>ASSISTANT</role>"
GEN_BUCKETS = (128, 192, 256, 384, 512, 768, 1024, 1536, 2048)  # canvas sizes; a piece gets the smallest that fits 2.5x it

device = torch.device(0)
tokenizer = AutoTokenizer.from_pretrained(REPO, trust_remote_code=True)

import os
os.environ.update(MASTER_ADDR="localhost", MASTER_PORT="45611")
distributed.init_distributed_environment(1, 0, "env://", 0, "nccl")
distributed.initialize_model_parallel(1, backend="nccl")

with torch.no_grad(), set_current_vllm_config(VllmConfig(parallel_config=ParallelConfig(enable_expert_parallel=True))):
    config = AutoConfig.from_pretrained(REPO, trust_remote_code=True)
    model = LLaDAMoeModelLM(config=config).eval()
    model.load_weights(REPO, torch_dtype=torch.bfloat16)  # downloads the fused shards from this repo
    model = model.to(device)
    model(torch.arange(178, device=device).unsqueeze(0), use_cache=False)  # warmup, both cache paths
    model(torch.arange(178, device=device).unsqueeze(0), use_cache=True)
    model.forward = torch.compile(model.forward, mode="reduce-overhead", fullgraph=False, dynamic=True)

    decoder = ThresholdParallelDecoder(temperature=0, threshold=0.95, mask_id=MASK_ID, eos_id=EOS_ID)
    dllm = IterSmoothWithVicinityCacheDiffusionLLM(
        model, decoder, BlockIteratorFactory(start_block_align=True),
        cache_factory=KVCacheFactory("dual", is_bd_model=False), early_stop=True,
        cont_weight=0.3, prefix_look=16, after_look=16, warmup_steps=4,
    )

    def translate_batch(texts: list[str]) -> list[str]:
        """Decodes several pieces in parallel as one batch; the canvas is sized for the longest one (2.5x its
        source tokens — an oversized canvas makes this bidirectional model repeat/duplicate instead of stopping)."""
        ids = [tokenizer(PROMPT.format(t))["input_ids"] for t in texts]
        longest_src = max(len(tokenizer(t)["input_ids"]) for t in texts)
        width = max(len(i) for i in ids)
        gen = next((g for g in GEN_BUCKETS if g >= 2.5 * longest_src), GEN_BUCKETS[-1])
        gen = max(BLOCK, ((width + gen) // 32) * 32 - width)
        batch = torch.full((len(ids), width), MASK_ID, dtype=torch.long, device=device)
        for j, row in enumerate(ids):
            batch[j, : len(row)] = torch.tensor(row, device=device)
        out = dllm.generate(batch, gen_length=gen, block_length=BLOCK)
        return [tokenizer.decode(out[j, len(row):], skip_special_tokens=True).strip() for j, row in enumerate(ids)]

    def translate_cot(chain_of_thought: str, cap: int = 450) -> str:
        """Chunks a long CoT into <=cap-token steps at paragraph/sentence boundaries, translates the chunked
        pieces in one batch, and rejoins them with the original whitespace."""
        count = lambda t: len(tokenizer(t)["input_ids"])
        pieces, seps = split_text(chain_of_thought, count, cap)
        return join_pieces(translate_batch(pieces), seps)


cot = """Wait, let me recompute the sum. We have a_n = n^2 + 3n - 1 for n = 1..5.

For n=1: 1 + 3 - 1 = 3. For n=2: 4 + 6 - 1 = 9. For n=3: 9 + 9 - 1 = 17.
Adding these up: 3 + 9 + 17 = 29 so far.

So the total for n=1..3 is 29, and we still need n=4 and n=5."""

print(translate_cot(cot))

translate_cot chunks the reasoning trace into paragraph/sentence-bounded pieces of at most cap tokens (450 by default — the training data's English steps run up to 1024 tokens, but a smaller cap keeps the canvas tight and reduces the duplication this model shows when given more room than it needs), decodes all the pieces from a document together as one batch, and stitches the Hindi back together with the original whitespace.

Serving multiple requests

For interactive use (a chat app, a translation endpoint) keep the model loaded once and reuse translate_batch / translate_cot across requests rather than reloading per call — model load + torch.compile warmup takes a few minutes. A minimal reference HTTP server that does this (plus request batching by canvas size, so many small steps share one generate() call) is at dinfer_server.py in the training repo.

Notes / known limitations

  • This is a step translator, not a document translator. It was trained on individual chain-of-thought steps (median ~130 English tokens), not whole multi-thousand-token documents in one shot. Always chunk first.
  • Canvas duplication. Being bidirectional, this model decodes into a canvas of fixed length chosen before generation starts. Too large a canvas relative to what the translation needs makes it repeat or duplicate content instead of stopping early. translate_batch above sizes the canvas per batch (2.5x the longest source piece); chunking first (via translate_cot) keeps that multiplier from blowing up on long inputs.
  • Threshold decoding commits several tokens per step once their confidence passes the threshold (0.95 above); this is what gives the speed-up over one-token-per-step sampling, at a small quality cost versus the slower sampler on the same checkpoint (evaluated with an LLM-judge on a 20-step held-out sample: ~0.39 vs ~0.41 mean judged-correctness, 6/20 vs 9/20 judged fully correct — noisy at this sample size).
  • License is inherited from the Apache-2.0 base model.

Как запустить

На своей GPU в ailist. Цена — по текущим предложениям провайдеров

GPU в ailist

Универсальный рантайм

Нельзя запустить

Модели нужен код из репозитория; запуск откроется после проверки совместимости.

Класс архитектуры
FusedLLaDAMoEModelLM
Ревизия весов
31ac387

0 моделей