Dhฤซr 2B โ€” ONNX

ONNX exports of adityabhushannagar/Dhir-2B for ONNX Runtime. Weights are unchanged apart from the stated quantization. The export runs without PyTorch, without transformers and without trust_remote_code.

All credit for the model goes to its original authors (ZenteiQ AiTech Innovations, BrahmAI family, Apache 2.0); see the original model card for intended use, evaluations and precautions.

Variants

variant file size weights fidelity vs. original (PyTorch fp32)
q4 onnx/model_q4.onnx 1.84 GB int4 everywhere top-1 83/98, KL 0.130
mixed onnx/model_mixed.onnx 2.21 GB int8 attention + lm_head + first/last-layer MLP, int4 other MLP top-1 87/98, KL 0.068
q8 onnx/model_q8.onnx 2.89 GB int8 everywhere top-1 97/98, KL 0.0018
fp32 onnx/model.onnx 8.12 GB float32 exact: max logit diff โ‰ค 4e-4, top-1 50/50

Fidelity is measured against the original PyTorch model (fp32), teacher-forced on a left-padded batch of two long-form prompts (English and Hindi) over 49 KV-cached decode steps. top-1 counts steps where the ONNX model's argmax token equals the original's. KL is the mean KL(original โ€– ONNX) of the next-token distribution.

Picking one: q4 is smallest and fastest; mixed is the best size/quality trade-off; q8 is near-lossless; fp32 is the full-precision reference.

Single-stream CPU decode speed (4 vCPU, onnxruntime 1.31.1, 64 new tokens): q4 13.0 tok/s, mixed 11.4, q8 10.5, fp32 3.0.

In every quantized variant the embedding table is stored as fp16, and norms and the KV cache stay fp32. Quantization is round-to-nearest with block size 32 (MatMulNBits asymmetric). mixed uses 8-bit for all attention projections, lm_head, and the MLP of the first and last layer, and 4-bit for the remaining MLP weights.

Uses com.microsoft.MatMulNBits for quantized linear layers (the fp32 model uses only standard ONNX ops). Tested on CPU with onnxruntime 1.31.1.

Quick start

pip install onnxruntime tokenizers jinja2 huggingface_hub numpy
# download one variant + tokenizer/config files and chat (streams tokens)
python generate_onnx.py --model adityabhushannagar/Dhir-2B-ONNX --variant q4 --prompt "เคญเคพเคฐเคค เค•เฅ€ เคฐเคพเคœเคงเคพเคจเฅ€ เค•เฅ‡ เคฌเคพเคฐเฅ‡ เคฎเฅ‡เค‚ เคฆเฅ‹ เคตเคพเค•เฅเคฏ เคฒเคฟเค–เคฟเคเฅค"

(generate_onnx.py is in this repo: hf download adityabhushannagar/Dhir-2B-ONNX generate_onnx.py --local-dir .. With a repo id it downloads into ./Dhir-2B-ONNX; it can also be pointed at a local directory.)

To fetch files yourself, use hf download adityabhushannagar/Dhir-2B-ONNX --include "onnx/model_q4.onnx*" "*.json" "*.jinja" --local-dir Dhir-2B-ONNX. Always pass --local-dir/local_dir: recent onnxruntime versions (e.g. 1.31) refuse external weights reached through the Hugging Face cache's symlinks ("External data path escapes model directory").

From Python

from huggingface_hub import snapshot_download
from generate_onnx import DhirONNX

# local_dir matters: recent onnxruntime refuses external weight files reached through the HF cache's symlinks
path = snapshot_download("adityabhushannagar/Dhir-2B-ONNX", allow_patterns=["*.json", "*.jinja", "*.py", "onnx/model_q4.onnx*"],
                         local_dir="Dhir-2B-ONNX")
llm = DhirONNX(path, variant="q4")          # "q4" | "mixed" | "q8" | "fp32"

print(llm.chat([{"role": "user", "content": "Explain photosynthesis in two sentences."}], max_new_tokens=128))

Tool / function calling

The model's native tool format is preserved (same chat template as the original):

tools = [{"type": "function", "function": {
    "name": "get_weather", "description": "Get current weather for a city",
    "parameters": {"type": "object", "properties": {"city": {"type": "string"}}, "required": ["city"]}}}]

msgs = [{"role": "user", "content": "What's the weather in Bengaluru?"}]
print(llm.chat(msgs, tools=tools))
# -> <tool_call>{"name": "get_weather", "arguments": {"city": "Bengaluru"}}</tool_call>

msgs += [{"role": "assistant", "content": "", "tool_calls": [{"type": "function", "function": {
            "name": "get_weather", "arguments": {"city": "Bengaluru"}}}]},
         {"role": "tool", "content": '{"temp_c": 27, "sky": "cloudy"}'}]
print(llm.chat(msgs, tools=tools))

DhirONNX.render() reproduces tokenizer.apply_chat_template token for token (checked against transformers). With transformers installed, PreTrainedTokenizerFast.from_pretrained(path) also works for tokenization and apply_chat_template (no remote code needed).

Raw ONNX Runtime loop (any language)

The graph is a standard decoder with KV cache, using the same I/O names as Optimum / transformers.js exports:

name shape dtype
input_ids (in) [batch, seq] int64
attention_mask (in) [batch, past + seq] int64 (1 = token, 0 = padding)
position_ids (in) [batch, seq] int64
past_key_values.{i}.key / .value (in), i = 0..27 [batch, 8, past, 128] float32
logits (out) [batch, seq, 131072] float32
present.{i}.key / .value (out) [batch, 8, past + seq, 128] float32
import numpy as np, onnxruntime as ort
from tokenizers import Tokenizer

sess = ort.InferenceSession("onnx/model_q4.onnx", providers=["CPUExecutionProvider"])
tok = Tokenizer.from_file("tokenizer.json")
ids = tok.encode("<bos><|user|>Hello!<|end_of_turn|><|assistant|><|nothink|>", add_special_tokens=False).ids

feed = {"input_ids": np.array([ids]), "attention_mask": np.ones((1, len(ids)), np.int64),
        "position_ids": np.arange(len(ids))[None]}
for i in range(28):
    for kv in ("key", "value"):
        feed[f"past_key_values.{i}.{kv}"] = np.zeros((1, 8, 0, 128), np.float32)
names = [o.name for o in sess.get_outputs()]
out = []
for _ in range(64):
    res = dict(zip(names, sess.run(None, feed)))
    nxt = int(res["logits"][0, -1].argmax())
    if nxt in (1, 12):          # <eos>, <|end_of_turn|>
        break
    out.append(nxt)
    mask = np.ones((1, feed["attention_mask"].shape[1] + 1), np.int64)
    feed = {"input_ids": np.array([[nxt]]), "attention_mask": mask, "position_ids": np.array([[mask.shape[1] - 1]])}
    for i in range(28):
        for kv in ("key", "value"):
            feed[f"past_key_values.{i}.{kv}"] = res[f"present.{i}.{kv}"]
print(tok.decode(out))

Batched generation works with left padding: pass attention_mask with zeros on the padding and position_ids = cumsum(attention_mask) - 1 (clipped at 0).

The same graph runs from the C/C++, C#, Java and JavaScript (onnxruntime-node) ONNX Runtime APIs with the loop above.

Files

  • onnx/model*.onnx + onnx/model*.onnx_data*: graphs and external weights (keep each graph's data files next to it)
  • tokenizer.json, tokenizer_config.json, chat_template.jinja, config.json, generation_config.json: copied from the original repo
  • generate_onnx.py: dependency-light inference and chat helper
  • build_onnx.py: the converter used to produce these files (streams weights from the original safetensors): python build_onnx.py --model-dir <Dhir-2B checkout> --out-dir onnx --precision q4|q8|mixed|fp32

License

Apache 2.0, same as the original model.

Downloads last month
95
Inference Providers NEW
This model isn't deployed by any Inference Provider. ๐Ÿ™‹ Ask for provider support

Model tree for adityabhushannagar/Dhir-2B-ONNX

Quantized
(2)
this model