Views
No views yet
.mlpackage converted from google/gemma-3-1b-it for use with HuggingFace's AnyLanguageModel Swift framework and swift-transformers ≥ 1.0.inputIds / attentionMask / logits convention required by swift-transformers 1.x LanguageModel. Drop-in compatible with CoreMLLanguageModel(url:computeUnits:chatTemplateHandler:).grio-gemma-3-1b-coreml-anyLM-seq512 (this repo)
Fixed [1, 512] — short-form text enhancement / single-sentence translation. Smallest graph. Multiple safe backends.grio-gemma-3-1b-coreml-anyLM-seq1024
Fixed [1, 1024] — medium-context post-processing.grio-gemma-3-1b-coreml-anyLM-seq2048
RangeDim [1, 1..2048] — variable-length / long-context. Per-step cost scales with actual prompt length; fastest for typical product prompts. Must use .cpuAndGPU on the RangeDim variant.| Spec | Value |
|---|---|
| Base | google/gemma-3-1b-it |
| Precision | Float16 (mlprogram) |
| Context | 512 tokens, fixed shape (prompt + completion combined) |
| Inputs | inputIds, attentionMask |
| Input shape | Int32 [1, 512] |
| Output | logits: Float16 [1, 512, 262144] (rank-3, per-position) |
| Min OS | iOS 18 / macOS 15 |
| Compute | .cpuAndGPU fastest; .cpuOnly and .all also work |
| Format | .mlpackage (compiled on first load) |
| Toolchain | coremltools 9.0 + torch 2.7 + transformers 5.8.1 |
.mlpackage. Output is byte-identical to the matching seq1024 and seq2048 variants in this collection (same weights, same graph topology; only the static seq dimension differs)."You are a helpful assistant. Answer concisely."
User: "What is the capital of France?"
Output: "Paris." (stops at <end_of_turn> after 3 tokens)seq2048 variant card for the full translation + post-processing verified-output table — outputs are byte-identical between variants.| Compute | Predict | Load | Result |
|---|---|---|---|
.cpuAndGPU | ~1106 | ~12s | ✅ Clean. Fastest. |
.cpuOnly | ~1106 | ~9s | ✅ Clean output (fixed-shape variant; FP16 BNNS path is healthy at this scale). |
.all | ~1869 | ~197s | ✅ Clean output but ANE compilation fails internally; CoreML silently falls back to GPU/CPU. Very slow load. |
.cpuAndNE | ~2883 | ~156s | ⚠️ Clean output but ANE compilation slow. |
Smoke runs pad to the full 512-position graph every step, so the ms/tok number reflects fixed-shape compute over 512 positions. For typical product prompts (<200 tokens), theseq2048RangeDim variant is faster.
seq2048 RangeDim variant in this collection (where .cpuOnly silently produces wrong output and .cpuAndNE errors). Choose by perf, not correctness — .cpuAndGPU is fastest.attentionMask = 0 on padded positions. The conversion script's smoke harness does this automatically.logits is per-position, rank-3 [1, 512, 262144]. Pick the row at the last real prompt token for greedy/sampled decode.<eos> (id 1) for general end-of-sequence and <end_of_turn> (id 106) for chat-turn termination. generation_config.json lists both. If your runtime stops only on tokenizer.eos_token_id (which returns <eos>), the model will decode past <end_of_turn> into out-of-distribution territory and produce multilingual gibberish that looks like graph corruption but isn't. Read the full eos_token_id list from generation_config.json. swift-transformers ≥ 1.3 handles this correctly.chat_template.jinja (a separate file from tokenizer_config.json). swift-transformers ≥ 1.3 reads it correctly. Older callers that only look in tokenizer_config.json will not find an inline template.attn_implementation="sdpa" — gives a cleaner, fewer-op MIL graph that lowers reliably.torch.export.default_decompositions() — the all-decompositions mode ({}) can SIGSEGV at 1B+ scale.optimize_repeat_ops.py:433 RuntimeWarning: overflow encountered in cast fires during conversion of this model. Despite the warning, output is byte-identical to PyTorch FP16 reference. Don't reflexively reconvert on seeing it — verify with a PyTorch comparison instead..all works on seq512, errors on seq1024. Always sweep your build before recommending a backend.chat_template.jinja must be bundled alongside the .mlpackage. So must generation_config.json, special_tokens_map.json, added_tokens.json, tokenizer.model. All included in this repo.1import AnyLanguageModel
2
3let modelURL: URL = // path to this .mlpackage on disk
4let lm = try await CoreMLLanguageModel(
5 url: modelURL,
6 computeUnits: .cpuAndGPU,
7 chatTemplateHandler: { instructions, prompt in
8 // Gemma 3 uses its own <start_of_turn>...<end_of_turn> chat template;
9 // swift-transformers loads it from chat_template.jinja at runtime.
10 var messages: [Message] = []
11 if let system = instructions?.description, !system.isEmpty {
12 messages.append(["role": "system", "content": system])
13 }
14 messages.append(["role": "user", "content": prompt.description])
15 return messages
16 }
17)
18let session = LanguageModelSession(model: lm, instructions: "You are a helpful assistant.")
19let response = try await session.respond(to: "Improve this text: …")
20print(response.content)tokenizer.json, tokenizer_config.json, config.json, chat_template.jinja, generation_config.json, special_tokens_map.json, added_tokens.json, and tokenizer.model (all bundled in this repo) as siblings of the .mlpackage on disk.coremltools==9.0, torch==2.7.0, transformers==5.8.1. Approximate single-call recipe:1import coremltools as ct, torch, torch.nn as nn
2from transformers import AutoModelForCausalLM
3
4model = AutoModelForCausalLM.from_pretrained(
5 "google/gemma-3-1b-it",
6 torch_dtype=torch.float16,
7 attn_implementation="sdpa",
8)
9model.eval()
10
11class Wrapper(nn.Module):
12 def __init__(self, m): super().__init__(); self.m = m
13 def forward(self, inputIds, attentionMask):
14 return self.m(input_ids=inputIds, attention_mask=attentionMask, use_cache=False).logits
15
16wrapper = Wrapper(model).eval()
17ep = torch.export.export(
18 wrapper,
19 (torch.randint(0, 262144, (1, 128), dtype=torch.int32),
20 torch.ones((1, 128), dtype=torch.int32)),
21).run_decompositions(torch.export.default_decompositions())
22
23ct.convert(
24 ep,
25 inputs=[
26 ct.TensorType(name="inputIds", shape=(1, 512), dtype=int),
27 ct.TensorType(name="attentionMask", shape=(1, 512), dtype=int),
28 ],
29 outputs=[ct.TensorType(name="logits")],
30 minimum_deployment_target=ct.target.iOS18,
31 compute_precision=ct.precision.FLOAT16,
32 convert_to="mlprogram",
33)google/gemma-3-1b-it by Google DeepMind. Re-uploaded as a CoreML port; original model card terms apply. By using this model you agree to Google's Gemma Terms of Use and the Prohibited Use Policy.