vukrosic commited on
Commit
4e47de6
·
verified ·
1 Parent(s): f598f3d

nano-dates: 1M byte-level date->ISO parser (v3, honest data)

Browse files
Files changed (4) hide show
  1. README.md +124 -0
  2. config.json +33 -0
  3. model.safetensors +3 -0
  4. modeling_nano_dates.py +165 -0
README.md ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: mit
3
+ language:
4
+ - en
5
+ tags:
6
+ - tiny
7
+ - nano-llm
8
+ - dates
9
+ - structured-output
10
+ - byte-level
11
+ - from-scratch
12
+ pipeline_tag: text2text-generation
13
+ library_name: safetensors
14
+ ---
15
+
16
+ # nano-dates
17
+
18
+ A **1,016,960-parameter** (~1M) byte-level transformer that converts a natural date
19
+ phrase to an **ISO-8601** date. It is small enough to run on a CPU in milliseconds
20
+ and was trained **entirely on code-generated data** — no scraping, no labelling, no
21
+ distillation from a larger model.
22
+
23
+ ```
24
+ 2024-03-10 | the 3rd of July 2025 => 2025-07-03
25
+ 2024-03-10 | Jun 12 2023 => 2023-06-12
26
+ 2024-03-10 | next week => 2024-03-17
27
+ 2024-03-10 | in 3 months => 2024-06-10
28
+ ```
29
+
30
+ The model is given a **reference date** (`today`) at the start of the prompt, so
31
+ relative phrases ("tomorrow", "in 3 weeks") are computable from the input alone —
32
+ it never needs a wall clock.
33
+
34
+ ## Why this exists
35
+
36
+ A 1M-parameter model can't be a general assistant, but it *can* completely nail a
37
+ task that is **narrow and formally specified**. Date→ISO is exactly that: the
38
+ answer has a known structure, so you can **sample the answer first and render it in
39
+ many natural forms**, producing perfectly-labelled training data for free and in
40
+ unlimited quantity. That is strictly better than asking a big model to generate
41
+ data — the label *is* the ground truth, not a guess.
42
+
43
+ This model is a worked demonstration of that recipe (and an honest map of where a
44
+ nano model's capability ends — see below).
45
+
46
+ ## What it can and can't do
47
+
48
+ Held-out exact-match accuracy (2,000 unseen examples, greedy decode):
49
+
50
+ | capability | category | accuracy |
51
+ |---|---|---|
52
+ | **Parse absolute dates** | `2023-06-12`, `June 12, 2023`, `Jun 12 2023`, `12 June 2023`, `the 12th of June 2023` | **100%** |
53
+ | **Resolve simple relatives** | today, tomorrow, yesterday, next/last week, next month, in N months | **98–100%** |
54
+ | **Variable-N day/week arithmetic** | in N days, N days ago, in N weeks | **77–81%** |
55
+ | **Weekday resolution** | next/last \<weekday\> | **~12%** ❌ |
56
+ | **Overall** | mixed | **85.4%** |
57
+
58
+ The clean limitation: **weekday resolution** ("next friday") is unsolved at this
59
+ size. It requires mapping an arbitrary date to its weekday and then doing modular
60
+ arithmetic — the hardest computation in the set — and a 1M model doesn't get there.
61
+ Everything else, including the absolute-form parsing and most relative arithmetic,
62
+ it does reliably. The accuracy numbers reflect **genuine parsing**: absolute phrases
63
+ are trained with a reference date *independent* of the answer, so the model cannot
64
+ cheat by copying the prompt.
65
+
66
+ ## Usage
67
+
68
+ The repo includes a **self-contained** model definition (`modeling_nano_dates.py`)
69
+ — no training framework required, just `torch` and `safetensors`.
70
+
71
+ ```python
72
+ from modeling_nano_dates import load, parse
73
+
74
+ model = load("model.safetensors", "config.json")
75
+ print(parse(model, "2024-03-10", "the 3rd of July 2025")) # -> 2025-07-03
76
+ print(parse(model, "2024-03-10", "in 3 weeks")) # -> 2024-03-31
77
+ ```
78
+
79
+ Or just run the file for a demo: `python modeling_nano_dates.py`.
80
+
81
+ Prompt format the model was trained on (byte-for-byte):
82
+
83
+ ```
84
+ <reference ISO date> | <phrase> => <answer ISO date>
85
+ ```
86
+
87
+ `parse()` builds that prompt and greedily decodes exactly 10 characters.
88
+
89
+ ## Model details
90
+
91
+ | | |
92
+ |---|---|
93
+ | Parameters | 1,016,960 |
94
+ | Architecture | decoder-only transformer (pre-norm) |
95
+ | Tokenizer | raw UTF-8 bytes (vocab 256, no vocab file) |
96
+ | dim / layers / heads | 128 / 4 / 4 (2 KV heads, GQA) |
97
+ | Norm / position / FFN | RMSNorm / RoPE / SwiGLU |
98
+ | Context | 64 bytes |
99
+ | Training | SFT, prompt-masked cross-entropy, 12k steps, AdamW, cosine LR 3e-3 |
100
+ | Data | 100k code-generated pairs, 17 surface renderers |
101
+ | Final val loss | 0.036 |
102
+
103
+ ## Limitations & honest scope
104
+
105
+ - **Not a production date library.** For real software, `dateutil`/`chrono` are
106
+ exact and free. This model's value is as a *method demonstration* and a study of
107
+ what a nano model can learn from synthetic data, not as a dependency.
108
+ - **Weekday phrases ("next friday") are unreliable** (~12%). Don't use them.
109
+ - **English only**, and only the 17 surface forms it was trained on. It has not
110
+ seen "12/06/2023"-style numeric forms (deliberately — they're ambiguous).
111
+ - Reference dates were drawn from **2015–2035**; far outside that, behaviour is
112
+ untested.
113
+
114
+ ## What should this method point at next?
115
+
116
+ The interesting question isn't this model — it's the *recipe*. If you have a
117
+ **narrow, formal, annoying task** you wish a tiny reliable model could do (parse,
118
+ normalize, validate, convert), that's exactly the shape this approach fits. Tell me
119
+ what it is — open a discussion on this repo.
120
+
121
+ ---
122
+
123
+ *Built from scratch with [voidlab](https://github.com/vukrosic). Trained on a single
124
+ GPU in ~30 seconds.*
config.json ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "model_type": "nano-dates",
3
+ "architecture": "decoder-only transformer (pre-norm)",
4
+ "vocab_size": 256,
5
+ "tokenizer": "byte (raw UTF-8 bytes, no vocab file)",
6
+ "dim": 128,
7
+ "n_layers": 4,
8
+ "n_heads": 4,
9
+ "n_kv_heads": 2,
10
+ "head_dim": 32,
11
+ "ffn": "swiglu",
12
+ "ffn_mult": 4,
13
+ "norm": "rmsnorm",
14
+ "norm_eps": 1e-05,
15
+ "positional": "rope",
16
+ "rope_theta": 10000.0,
17
+ "max_seq_len": 64,
18
+ "tie_word_embeddings": true,
19
+ "params": 1016960,
20
+ "training": {
21
+ "task": "natural date phrase -> ISO 8601",
22
+ "data": "100% code-generated (answer sampled first, then rendered in 17 natural forms)",
23
+ "objective": "SFT, prompt-masked cross-entropy (only the 10-char ISO target is supervised)",
24
+ "steps": 12000,
25
+ "batch_size": 64,
26
+ "seq_len": 64,
27
+ "optimizer": "adamw",
28
+ "lr": 0.003,
29
+ "schedule": "cosine",
30
+ "warmup_steps": 200,
31
+ "final_val_loss": 0.0358
32
+ }
33
+ }
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b59fd7f9cd229a302a748268bc96f8a04af580a38e6b808a4aa45fbfd0934bec
3
+ size 4071464
modeling_nano_dates.py ADDED
@@ -0,0 +1,165 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Self-contained nano-dates model — no dependencies beyond torch + safetensors.
2
+
3
+ A 1M-parameter byte-level decoder-only transformer (RMSNorm, RoPE, GQA, SwiGLU)
4
+ that converts a natural date phrase to an ISO-8601 date. This single file vendors
5
+ the exact architecture the model was trained with, so you can load and run the
6
+ published weights without installing the training lab.
7
+
8
+ python modeling_nano_dates.py # runs a few examples
9
+ # or, from your own code:
10
+ from modeling_nano_dates import load, parse
11
+ model = load("model.safetensors", "config.json")
12
+ print(parse(model, "2024-03-10", "the 3rd of July 2025")) # -> 2025-07-03
13
+
14
+ Prompt format the model was trained on (byte-for-byte):
15
+
16
+ <today ISO> | <phrase> => <answer ISO>
17
+
18
+ `today` is given so relative phrases ("tomorrow", "next week") are computable from
19
+ the input alone — the model never needs a wall clock. `parse()` builds the prompt
20
+ and greedily decodes exactly 10 characters.
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ import json
26
+
27
+ import torch
28
+ import torch.nn as nn
29
+ import torch.nn.functional as F
30
+
31
+
32
+ class RMSNorm(nn.Module):
33
+ def __init__(self, dim: int, eps: float = 1e-5):
34
+ super().__init__()
35
+ self.eps = eps
36
+ self.weight = nn.Parameter(torch.ones(dim))
37
+
38
+ def forward(self, x):
39
+ rms = x.float().pow(2).mean(-1, keepdim=True).add(self.eps).rsqrt()
40
+ return (x.float() * rms).type_as(x) * self.weight
41
+
42
+
43
+ class RoPE(nn.Module):
44
+ def __init__(self, head_dim: int, max_seq_len: int, theta: float = 10000.0):
45
+ super().__init__()
46
+ inv_freq = 1.0 / (theta ** (torch.arange(0, head_dim, 2).float() / head_dim))
47
+ freqs = torch.outer(torch.arange(max_seq_len).float(), inv_freq)
48
+ self.register_buffer("cos", freqs.cos(), persistent=False)
49
+ self.register_buffer("sin", freqs.sin(), persistent=False)
50
+
51
+ def apply(self, x, offset: int = 0):
52
+ seq = x.size(-2)
53
+ cos = self.cos[offset:offset + seq]
54
+ sin = self.sin[offset:offset + seq]
55
+ x1, x2 = x[..., 0::2], x[..., 1::2]
56
+ rot1 = x1 * cos - x2 * sin
57
+ rot2 = x1 * sin + x2 * cos
58
+ return torch.stack((rot1, rot2), dim=-1).flatten(-2).type_as(x)
59
+
60
+
61
+ class GQA(nn.Module):
62
+ def __init__(self, dim, n_heads, n_kv_heads, head_dim, positional):
63
+ super().__init__()
64
+ self.n_heads, self.n_kv_heads, self.head_dim = n_heads, n_kv_heads, head_dim
65
+ self.n_rep = n_heads // n_kv_heads
66
+ self.positional = positional
67
+ self.q_proj = nn.Linear(dim, n_heads * head_dim, bias=False)
68
+ self.k_proj = nn.Linear(dim, n_kv_heads * head_dim, bias=False)
69
+ self.v_proj = nn.Linear(dim, n_kv_heads * head_dim, bias=False)
70
+ self.o_proj = nn.Linear(n_heads * head_dim, dim, bias=False)
71
+
72
+ def forward(self, x, mask):
73
+ b, seq, _ = x.shape
74
+ q = self.q_proj(x).view(b, seq, self.n_heads, self.head_dim).transpose(1, 2)
75
+ k = self.k_proj(x).view(b, seq, self.n_kv_heads, self.head_dim).transpose(1, 2)
76
+ v = self.v_proj(x).view(b, seq, self.n_kv_heads, self.head_dim).transpose(1, 2)
77
+ q = self.positional.apply(q)
78
+ k = self.positional.apply(k)
79
+ if self.n_rep > 1:
80
+ k = k.repeat_interleave(self.n_rep, dim=1)
81
+ v = v.repeat_interleave(self.n_rep, dim=1)
82
+ scores = (q @ k.transpose(-2, -1)) / (self.head_dim ** 0.5)
83
+ if mask is not None:
84
+ scores = scores + mask
85
+ out = F.softmax(scores, dim=-1) @ v
86
+ out = out.transpose(1, 2).reshape(b, seq, self.n_heads * self.head_dim)
87
+ return self.o_proj(out)
88
+
89
+
90
+ class SwiGLU(nn.Module):
91
+ def __init__(self, dim: int, hidden: int):
92
+ super().__init__()
93
+ self.gate = nn.Linear(dim, hidden, bias=False)
94
+ self.up = nn.Linear(dim, hidden, bias=False)
95
+ self.down = nn.Linear(hidden, dim, bias=False)
96
+
97
+ def forward(self, x):
98
+ return self.down(F.silu(self.gate(x)) * self.up(x))
99
+
100
+
101
+ class Block(nn.Module):
102
+ def __init__(self, cfg, positional):
103
+ super().__init__()
104
+ hidden = int(cfg["dim"] * cfg["ffn_mult"])
105
+ self.attn_norm = RMSNorm(cfg["dim"], cfg["norm_eps"])
106
+ self.attn = GQA(cfg["dim"], cfg["n_heads"], cfg["n_kv_heads"], cfg["head_dim"], positional)
107
+ self.ffn_norm = RMSNorm(cfg["dim"], cfg["norm_eps"])
108
+ self.ffn = SwiGLU(cfg["dim"], hidden)
109
+
110
+ def forward(self, x, mask):
111
+ x = x + self.attn(self.attn_norm(x), mask)
112
+ x = x + self.ffn(self.ffn_norm(x))
113
+ return x
114
+
115
+
116
+ class NanoDates(nn.Module):
117
+ def __init__(self, cfg: dict):
118
+ super().__init__()
119
+ self.cfg = cfg
120
+ self.tok_emb = nn.Embedding(cfg["vocab_size"], cfg["dim"])
121
+ self.positional = RoPE(cfg["head_dim"], cfg["max_seq_len"], cfg["rope_theta"])
122
+ self.blocks = nn.ModuleList([Block(cfg, self.positional) for _ in range(cfg["n_layers"])])
123
+ self.final_norm = RMSNorm(cfg["dim"], cfg["norm_eps"])
124
+ self.lm_head = nn.Linear(cfg["dim"], cfg["vocab_size"], bias=False)
125
+ self.lm_head.weight = self.tok_emb.weight # tied
126
+
127
+ def forward(self, tokens):
128
+ seq = tokens.size(1)
129
+ x = self.tok_emb(tokens)
130
+ mask = torch.triu(torch.full((seq, seq), float("-inf"), device=tokens.device), diagonal=1)
131
+ for block in self.blocks:
132
+ x = block(x, mask)
133
+ return self.lm_head(self.final_norm(x))
134
+
135
+
136
+ def load(weights="model.safetensors", config="config.json", device="cpu"):
137
+ from safetensors.torch import load_file
138
+ with open(config) as f:
139
+ cfg = json.load(f)
140
+ model = NanoDates(cfg).to(device)
141
+ sd = load_file(weights)
142
+ sd["lm_head.weight"] = sd["tok_emb.weight"] # restore tied weight
143
+ model.load_state_dict(sd)
144
+ model.eval()
145
+ return model
146
+
147
+
148
+ @torch.no_grad()
149
+ def parse(model, today_iso: str, phrase: str, device="cpu") -> str:
150
+ """`today_iso` like '2024-03-10', `phrase` like 'next friday' -> 10-char ISO."""
151
+ prompt = f"{today_iso} | {phrase} => "
152
+ toks = torch.tensor([list(prompt.encode("utf-8"))], dtype=torch.long, device=device)
153
+ max_seq = model.cfg["max_seq_len"]
154
+ for _ in range(10):
155
+ nxt = model(toks[:, -max_seq:])[:, -1, :].argmax(-1, keepdim=True)
156
+ toks = torch.cat([toks, nxt], dim=1)
157
+ return bytes(int(b) & 0xFF for b in toks[0, -10:].tolist()).decode("utf-8", "replace")
158
+
159
+
160
+ if __name__ == "__main__":
161
+ m = load()
162
+ today = "2024-03-10"
163
+ for phrase in ["the 3rd of July 2025", "Jun 12 2023", "tomorrow", "yesterday",
164
+ "next week", "last week", "next month", "in 3 months"]:
165
+ print(f"{today} | {phrase:<22} -> {parse(m, today, phrase)}")