Jrffy666 commited on
Commit
f9740ea
·
verified ·
1 Parent(s): 84f4d5c

Publish audited SEDD-medium math-tool SFT inference weights

Browse files
LICENSE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Aaron Lou
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
MODEL_LICENSE.md ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Model-weight terms and scope
2
+
3
+ This repository contains two categories of material with different status.
4
+
5
+ ## Source code
6
+
7
+ The included SEDD implementation and loader are distributed with the MIT
8
+ license text in `LICENSE`. The retained upstream copyright is:
9
+
10
+ ```text
11
+ Copyright (c) 2024 Aaron Lou
12
+ ```
13
+
14
+ That license applies to the included software code. It does not, by itself,
15
+ establish the legal terms of pretrained or fine-tuned model weights.
16
+
17
+ ## Model weights
18
+
19
+ `model.safetensors` is a full-parameter derivative of
20
+ `louaaron/sedd-medium`. At packaging time, the upstream Hugging Face model card
21
+ did not declare a separate model-weight license in its YAML metadata. This
22
+ repository therefore does not relabel the derivative weights as MIT and does
23
+ not make an additional representation that their use, modification, or
24
+ redistribution is permitted for every purpose.
25
+
26
+ Before using or redistributing the weights, review the current upstream model
27
+ repository and obtain any permissions required for your use case. If the
28
+ upstream authors later clarify the applicable weight terms, those terms should
29
+ be followed. This notice is a scope clarification, not legal advice and not an
30
+ additional license grant.
31
+
32
+ Upstream model: <https://huggingface.co/louaaron/sedd-medium>
33
+
NOTICE.md ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Third-party and release notices
2
+
3
+ This model is a full-parameter fine-tune of **SEDD-medium** from Aaron Lou,
4
+ Chenlin Meng, and Stefano Ermon:
5
+
6
+ - Model repository: <https://huggingface.co/louaaron/sedd-medium>
7
+ - Pinned revision: `ce71a3c6178b50e899c8be1a1a4c13130308e54f`
8
+ - Base weight SHA-256:
9
+ `d93bb0dd1013295a4865848ea546ee3763a5be036cf55ea407e898c0a7a82a33`
10
+ - Base config SHA-256:
11
+ `f77926529f6ee5b913981775ebd2f8560c271341ad6dc67a0eab4c56eb032ec5`
12
+
13
+ The bundled implementation is derived from
14
+ **Score-Entropy-Discrete-Diffusion**. Its upstream MIT copyright and license
15
+ text are retained in `LICENSE`. See `MODEL_LICENSE.md` for the separate model
16
+ weight scope clarification.
17
+
18
+ The training-data generator was Google's **Mathematics Dataset** at commit
19
+ `427f45075f84b8b9774950196ad63867ca20ffb3`; that project is distributed under
20
+ Apache License 2.0. The generator source and full training data are not bundled
21
+ here. The configured GPT-2 tokenizer is also an external artifact and is not
22
+ redistributed by this model repository.
23
+
24
+ Release-specific loader and experiment code:
25
+ <https://github.com/Jrffy666/SEDD/tree/9b26b8980b298ce5cf08013320354ad4141796c1>
26
+
27
+ This release deliberately includes only the audited online inference weights.
28
+ It excludes the raw training checkpoint, optimizer, EMA, RNG state, private
29
+ paths and device identifiers, complete training data, and sealed evaluation
30
+ examples.
31
+
README.md CHANGED
@@ -1,3 +1,153 @@
1
  ---
2
- license: mit
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3
  ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ license: other
3
+ license_name: upstream-sedd-weight-terms-unspecified
4
+ license_link: https://huggingface.co/Jrffy666/SEDD-medium/blob/main/MODEL_LICENSE.md
5
+ base_model: louaaron/sedd-medium
6
+ base_model_relation: finetune
7
+ language:
8
+ - en
9
+ - zh
10
+ tags:
11
+ - pytorch
12
+ - safetensors
13
+ - discrete-diffusion
14
+ - sedd
15
+ - supervised-fine-tuning
16
+ - tool-use
17
+ - arithmetic
18
+ - research
19
  ---
20
+
21
+ # SEDD-medium Math Tool SFT
22
+
23
+ 这是 `louaaron/sedd-medium` 的全参数监督微调版本。模型学习的目标不是直接
24
+ 心算答案,而是在引用式协议中逐步产生工具动作;外部精确计算器执行
25
+ `ADD / SUB / MUL / DIV`,模型再引用工具结果给出最终答案。
26
+
27
+ ```text
28
+ Problem: 7 + 9 * 7
29
+ <CALL>MUL(x1,x2)</CALL> -> r0=63
30
+ <CALL>ADD(x0,r0)</CALL> -> r1=70
31
+ <FINAL>r1</FINAL>
32
+ ```
33
+
34
+ This repository contains the complete **online FP32 inference state**. It does
35
+ not contain the 6.79 GB training checkpoint, optimizer, EMA, RNG state, sealed
36
+ test prompts, or per-example evaluation traces. The upstream base weights are
37
+ not needed after loading this full-parameter state.
38
+
39
+ ## Artifact identity
40
+
41
+ | Item | Value |
42
+ |---|---|
43
+ | Architecture | SEDD-medium / DDiT, 24 blocks, hidden size 1024 |
44
+ | Parameters | 424,477,010 model parameters (+1 learned noise parameter) |
45
+ | Context length | 256 tokens |
46
+ | Weight variant | online FP32 |
47
+ | Weight tensors | 251 |
48
+ | `model.safetensors` | 1,697,932,808 bytes |
49
+ | Weight SHA-256 | `f3ee746f5ab56f8549592eca81bb33198b66ff16940cd6959e16943a5b06ee4a` |
50
+ | Source checkpoint SHA-256 | `020f76c434acb7652adcf0bc09f26c4605a00e7fe4462b6f71cea7f91438ebd5` |
51
+ | Reproducible code | [`Jrffy666/SEDD@9b26b898`](https://github.com/Jrffy666/SEDD/tree/9b26b8980b298ce5cf08013320354ad4141796c1) |
52
+
53
+ Machine-readable provenance, dimensions, file sizes, and hashes are in
54
+ `inference_metadata.json` and `checksums.sha256`.
55
+
56
+ ## Loading the weights
57
+
58
+ This is a custom SEDD architecture, **not** a Transformers `PreTrainedModel`.
59
+ `AutoModel.from_pretrained()` and the Hugging Face inference widget are not
60
+ supported. The included loader checks filenames, sizes, SHA-256 digests,
61
+ configuration schema, tensor keys, shapes, dtypes, and finite values before
62
+ moving the model to the requested device.
63
+
64
+ ```bash
65
+ pip install -r requirements.txt
66
+ hf download Jrffy666/SEDD-medium --local-dir ./SEDD-medium
67
+ ```
68
+
69
+ ```python
70
+ import sys
71
+ from pathlib import Path
72
+
73
+ snapshot = Path("./SEDD-medium").resolve()
74
+ sys.path.insert(0, str(snapshot))
75
+
76
+ from hf_model_loader import load_hf_sedd_model
77
+
78
+ model, graph, noise, config, metadata = load_hf_sedd_model(
79
+ snapshot,
80
+ device="cuda",
81
+ )
82
+ print(metadata["source"]["training_checkpoint_sha256"])
83
+ ```
84
+
85
+ The strict loader verifies roughly 1.70 GB of data and therefore performs a
86
+ full SHA-256 pass by default. Pass `verify=False` only if the surrounding
87
+ storage layer already provides equivalent integrity verification; structural
88
+ and dtype checks remain enabled.
89
+
90
+ For the tokenizer, reference-tool loop, exact `Fraction` calculator, training
91
+ pipeline, evaluation scripts, and FastAPI/React demo, use the
92
+ [`Jrffy666/SEDD`](https://github.com/Jrffy666/SEDD) source repository. The model
93
+ emits protocol actions rather than ordinary chat responses.
94
+
95
+ ## Training summary
96
+
97
+ - Base: `louaaron/sedd-medium`, pinned upstream revision
98
+ `ce71a3c6178b50e899c8be1a1a4c13130308e54f`.
99
+ - Data generator: Google DeepMind Mathematics Dataset, pinned commit
100
+ `427f45075f84b8b9774950196ad63867ca20ffb3`.
101
+ - Objective: reference-tool action SFT with exact rational execution targets.
102
+ - Adaptation: four-stage full-parameter curriculum (`400 / 1320 / 3440 / 600`
103
+ optimizer steps); final recovery stage observed 96,000 records.
104
+ - Final inference settings: GPT-2 tokenizer without added special tokens,
105
+ sequence length 256, Euler sampling configuration with 64 recorded steps.
106
+
107
+ Training inputs and the sealed evaluation panel are intentionally not bundled
108
+ with the model repository. Small reproducible smoke fixtures and integrity
109
+ commitments are available in the source repository.
110
+
111
+ ## Evaluation
112
+
113
+ The final online weights were evaluated once on a fixed, sealed 512-problem
114
+ seven-operation extrapolation panel. Only aggregate metrics are published.
115
+
116
+ | Metric | Result |
117
+ |---|---:|
118
+ | Final-answer accuracy | 237 / 512 (46.29%) |
119
+ | Completion rate | 444 / 512 (86.72%) |
120
+ | Exact oracle plan | 230 / 512 (44.92%) |
121
+ | Syntax-valid action turns | 98.24% |
122
+ | Previously unobserved suffix | 208 / 448 (46.43%) |
123
+
124
+ See `metrics.json` for the machine-readable aggregate report. These results
125
+ measure the complete model-plus-tool protocol on this specific generated panel;
126
+ they are not a general mathematics, reasoning, or natural-language benchmark.
127
+
128
+ ## Intended use and limitations
129
+
130
+ This release is intended for research, reproducibility, and demonstrations of
131
+ discrete-diffusion action generation. Important limits include:
132
+
133
+ - It is not a general conversational assistant and may emit invalid actions.
134
+ - The demonstrated agent accepts bounded integer arithmetic expressions using
135
+ `+`, `-`, `*`, `/`, and parentheses; natural-language word problems are not
136
+ claimed.
137
+ - Correct calculation is performed by an external deterministic tool. The
138
+ learned component plans and references calls; it does not guarantee a valid
139
+ plan or final answer.
140
+ - The published score comes from one fixed synthetic extrapolation panel and
141
+ should not be interpreted as broad mathematical understanding.
142
+ - Do not deploy in high-stakes settings without independent validation and
143
+ appropriate safeguards.
144
+
145
+ ## License and attribution
146
+
147
+ The included source code retains the upstream MIT license in `LICENSE`.
148
+ However, the upstream `louaaron/sedd-medium` Hugging Face repository did not
149
+ state a separate model-weight license in its card metadata when this derivative
150
+ release was packaged. The MIT code license must not be assumed to license the
151
+ weights. Read `MODEL_LICENSE.md` and `NOTICE.md` before using or redistributing
152
+ this artifact.
153
+
__pycache__/catsample.cpython-311.pyc ADDED
Binary file (1.25 kB). View file
 
__pycache__/graph_lib.cpython-311.pyc ADDED
Binary file (15.5 kB). View file
 
__pycache__/hf_model_loader.cpython-311.pyc ADDED
Binary file (15 kB). View file
 
__pycache__/noise_lib.cpython-311.pyc ADDED
Binary file (4.95 kB). View file
 
catsample.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn.functional as F
3
+
4
+
5
+ def gumbel_softmax(categorical_probs, hard=False, eps=1e-9):
6
+ logits = categorical_probs.clamp(min=1e-9).log()
7
+ return F.gumbel_softmax(logits, hard=hard)
8
+
9
+
10
+ def sample_categorical(categorical_probs, method="hard"):
11
+ if method == "hard":
12
+ gumbel_norm = 1e-10 - (torch.rand_like(categorical_probs) + 1e-10).log()
13
+ return (categorical_probs / gumbel_norm).argmax(dim=-1)
14
+ else:
15
+ raise ValueError(f"Method {method} for sampling categorical variables is not valid.")
16
+
checksums.sha256 ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ f3ee746f5ab56f8549592eca81bb33198b66ff16940cd6959e16943a5b06ee4a model.safetensors
2
+ 7559b29efa5cf3ab3ae472de3985faa543ece81f74eec9e1ba43a88265587261 noise.safetensors
3
+ e66555794ccb143ffe4654f10099238ab58465b56bb5fcabc6008a1b672b1e0c config.json
4
+ f315e172dc6f117b973e26137ee4a3b6396888f2586eb8bfd1d298fc81132f4b metrics.json
config.json ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "artifact_format": "sedd_math_tool_hf_inference_v1",
3
+ "graph": {
4
+ "type": "absorb"
5
+ },
6
+ "model": {
7
+ "cond_dim": 128,
8
+ "dropout": 0.0,
9
+ "hidden_size": 1024,
10
+ "length": 256,
11
+ "n_blocks": 24,
12
+ "n_heads": 16,
13
+ "name": "medium",
14
+ "scale_by_sigma": true,
15
+ "type": "ddit"
16
+ },
17
+ "noise": {
18
+ "sigma_max": 20.0,
19
+ "sigma_min": 0.0001,
20
+ "type": "loglinear"
21
+ },
22
+ "sampling": {
23
+ "eps": 0.001,
24
+ "noise_removal": true,
25
+ "predictor": "euler",
26
+ "steps": 64
27
+ },
28
+ "tokenizer": {
29
+ "add_special_tokens": false,
30
+ "identifier": "gpt2",
31
+ "vocab_sha256": "179cad62d906b7217f1c9431ece06e7a78a7721f9580960147a6c1ea0a53fc65"
32
+ },
33
+ "tokens": 50257
34
+ }
graph_lib.py ADDED
@@ -0,0 +1,267 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import abc
2
+ import torch
3
+ import numpy as np
4
+ import torch.nn as nn
5
+ import torch.nn.functional as F
6
+ from torch.cuda.amp import custom_fwd, custom_bwd
7
+
8
+
9
+ from catsample import sample_categorical
10
+
11
+ def get_graph(config, device):
12
+ if config.graph.type == "uniform":
13
+ return Uniform(config.tokens)
14
+ elif config.graph.type == "absorb":
15
+ return Absorbing(config.tokens)
16
+ else:
17
+ raise ValueError(f"Graph {config.graph.type} not valid")
18
+
19
+
20
+ def unsqueeze_as(x, y, back=True):
21
+ if back:
22
+ return x.view(*x.shape, *((1,) * (len(y.shape) - len(x.shape))))
23
+ else:
24
+ return x.view(*((1,) * (len(y.shape) - len(x.shape))), *x.shape)
25
+
26
+
27
+ class Graph(abc.ABC):
28
+
29
+ @property
30
+ def dim(self):
31
+ pass
32
+
33
+ @property
34
+ def absorb(self):
35
+ """
36
+ Whether input {dim - 1} is an absorbing state (used for denoising to always remove the mask).
37
+ """
38
+ pass
39
+
40
+
41
+ @abc.abstractmethod
42
+ def rate(self, i):
43
+ """
44
+ Computes the i-th column of the rate matrix Q, where i is [B_1, ..., B_n].
45
+
46
+ This is intended to compute the "forward" rate of p(X_t | X_0 = i).
47
+ """
48
+ pass
49
+
50
+
51
+ @abc.abstractmethod
52
+ def transp_rate(self, i):
53
+ """
54
+ Computes the i-th row of the rate matrix Q.
55
+
56
+ Can be used to compute the reverse rate.
57
+ """
58
+ pass
59
+
60
+
61
+ @abc.abstractmethod
62
+ def transition(self, i, sigma):
63
+ """
64
+ Computes the i-th column of the transition matrix e^{sigma Q}.
65
+ """
66
+ pass
67
+
68
+
69
+ def sample_transition(self, i, sigma):
70
+ """
71
+ Samples the transition vector.
72
+ """
73
+ transition_vector = self.transition(i, sigma)
74
+ return sample_categorical(transition_vector, method="hard")
75
+
76
+
77
+ def reverse_rate(self, i, score):
78
+ """
79
+ Constructs the reverse rate. Which is score * transp_rate
80
+ """
81
+ normalized_rate = self.transp_rate(i) * score
82
+
83
+ normalized_rate.scatter_(-1, i[..., None], torch.zeros_like(normalized_rate))
84
+ normalized_rate.scatter_(-1, i[..., None], -normalized_rate.sum(dim=-1, keepdim=True))
85
+ return normalized_rate
86
+
87
+ def sample_rate(self, i, rate):
88
+ return sample_categorical(F.one_hot(i, num_classes=self.dim).to(rate) + rate)
89
+
90
+
91
+ @abc.abstractmethod
92
+ def staggered_score(self, score, dsigma):
93
+ """
94
+ Computes p_{sigma - dsigma}(z) / p_{sigma}(x), which is approximated with
95
+ e^{-{dsigma} E} score
96
+ """
97
+ pass
98
+
99
+
100
+ @abc.abstractmethod
101
+ def sample_limit(self, *batch_dims):
102
+ """
103
+ Sample the limiting distribution. Returns the probability vector as well.
104
+ """
105
+ pass
106
+
107
+
108
+ @abc.abstractmethod
109
+ def score_entropy(self, score, sigma, x, x0):
110
+ """
111
+ Computes the score entropy function (with requisite constant normalization)
112
+ """
113
+ pass
114
+
115
+
116
+ class Uniform(Graph):
117
+ """
118
+ Everything goes to everything else. Normalized down by dimension to avoid blowup.
119
+ """
120
+ def __init__(self, dim):
121
+ self._dim = dim
122
+
123
+ @property
124
+ def dim(self):
125
+ return self._dim
126
+
127
+ @property
128
+ def absorb(self):
129
+ return False
130
+
131
+ def rate(self, i):
132
+ edge = torch.ones(*i.shape, self.dim, device=i.device) / self.dim
133
+ edge = edge.scatter(-1, i[..., None], - (self.dim - 1) / self.dim)
134
+ return edge
135
+
136
+ def transp_rate(self, i):
137
+ return self.rate(i)
138
+
139
+ def transition(self, i, sigma):
140
+ trans = torch.ones(*i.shape, self.dim, device=i.device) * (1 - (-sigma[..., None]).exp()) / self.dim
141
+ trans = trans.scatter(-1, i[..., None], torch.zeros_like(trans))
142
+ trans = trans.scatter(-1, i[..., None], 1 - trans.sum(dim=-1, keepdim=True))
143
+ return trans
144
+
145
+ def transp_transition(self, i, sigma):
146
+ return self.transition(i, sigma)
147
+
148
+ def sample_transition(self, i, sigma):
149
+ move_chance = 1 - (-sigma).exp()
150
+ move_indices = torch.rand(*i.shape, device=i.device) < move_chance
151
+ i_pert = torch.where(move_indices, torch.randint_like(i, self.dim), i)
152
+ return i_pert
153
+
154
+ def staggered_score(self, score, dsigma):
155
+ dim = score.shape[-1]
156
+ epow = (-dsigma).exp()[..., None]
157
+ return ((epow - 1) / (dim * epow)) * score.sum(dim=-1, keepdim=True) + score / epow
158
+
159
+ def sample_limit(self, *batch_dims):
160
+ return torch.randint(0, self.dim, batch_dims)
161
+
162
+ def score_entropy(self, score, sigma, x, x0):
163
+ esigm1 = torch.where(
164
+ sigma < 0.5,
165
+ torch.expm1(sigma),
166
+ torch.exp(sigma) - 1
167
+ )
168
+ ratio = 1 - self.dim / (esigm1 + self.dim)
169
+
170
+ # negative term
171
+ neg_term = score.mean(dim=-1) - torch.gather(score, -1, x[..., None]).squeeze(-1) / self.dim
172
+ # no move means scaling by the uniform ratio. move means alter only one ratio away from 1
173
+ neg_term = torch.where(
174
+ x == x0,
175
+ ratio * neg_term,
176
+ torch.gather(score, -1, x0[..., None]).squeeze(-1) / esigm1 + neg_term
177
+ )
178
+
179
+ # constant factor
180
+ const = torch.where(
181
+ x == x0,
182
+ (self.dim - 1) / self.dim * ratio * (ratio.log() - 1),
183
+ ((-ratio.log() - 1) / ratio - (self.dim - 2)) / self.dim
184
+ )
185
+
186
+ #positive term
187
+ sexp = score.exp()
188
+ pos_term = sexp.mean(dim=-1) - torch.gather(sexp, -1, x[..., None]).squeeze(-1) / self.dim
189
+ return pos_term - neg_term + const
190
+
191
+
192
+ class Absorbing(Graph):
193
+ def __init__(self, dim):
194
+ super().__init__()
195
+ self._dim = dim
196
+
197
+ @property
198
+ def dim(self):
199
+ return self._dim + 1
200
+
201
+ @property
202
+ def absorb(self):
203
+ return True
204
+
205
+ def rate(self, i):
206
+ # edge = - F.one_hot(i, num_classes=self.dim)
207
+ # edge.scatter_add_(-1, i[..., None], torch.ones_like(edge[..., :1]))
208
+ return F.one_hot((self.dim - 1) * torch.ones_like(i), num_classes=self.dim) - F.one_hot(i, num_classes=self.dim)
209
+
210
+ def transp_rate(self, i):
211
+ edge = -F.one_hot(i, num_classes=self.dim)
212
+ edge[i == self.dim - 1] += 1
213
+ return edge
214
+
215
+ def transition(self, i, sigma):
216
+ pass
217
+
218
+ def transp_transition(self, i, sigma):
219
+ sigma = unsqueeze_as(sigma, i[..., None])
220
+ edge = (-sigma).exp() * F.one_hot(i, num_classes=self.dim)
221
+ edge += torch.where(
222
+ i == self.dim - 1,
223
+ 1 - (-sigma).squeeze(-1).exp(),
224
+ 0
225
+ )[..., None]
226
+ return edge
227
+
228
+ def sample_transition(self, i, sigma):
229
+ move_chance = 1 - (-sigma).exp()
230
+ move_indices = torch.rand(*i.shape, device=i.device) < move_chance
231
+ i_pert = torch.where(move_indices, self.dim - 1, i)
232
+ return i_pert
233
+
234
+ def staggered_score(self, score, dsigma):
235
+ score = score.clone() # yeah yeah whatever we should probably do this
236
+ extra_const = (1 - (dsigma).exp()) * score.sum(dim=-1)
237
+ score *= dsigma.exp()[:, None]
238
+ score[..., -1] += extra_const
239
+ return score
240
+
241
+ def sample_limit(self, *batch_dims):
242
+ return (self.dim - 1) * torch.ones(*batch_dims, dtype=torch.int64)
243
+
244
+ def score_entropy(self, score, sigma, x, x0):
245
+ rel_ind = x == self.dim - 1
246
+ esigm1 = torch.where(
247
+ sigma < 0.5,
248
+ torch.expm1(sigma),
249
+ torch.exp(sigma) - 1
250
+ )
251
+
252
+ ratio = 1 / esigm1.expand_as(x)[rel_ind]
253
+ other_ind = x0[rel_ind]
254
+
255
+ # negative_term
256
+ neg_term = ratio * torch.gather(score[rel_ind], -1, other_ind[..., None]).squeeze(-1)
257
+
258
+ #positive term
259
+ pos_term = score[rel_ind][:, :-1].exp().sum(dim=-1)
260
+
261
+ # constant term
262
+ const = ratio * (ratio.log() - 1)
263
+
264
+ entropy = torch.zeros(*x.shape, device=x.device)
265
+ entropy[rel_ind] += pos_term - neg_term + const
266
+ return entropy
267
+
hf_model_loader.py ADDED
@@ -0,0 +1,258 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Strict loader for the inference-only Hugging Face SEDD artifact."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import json
7
+ import math
8
+ import re
9
+ from collections.abc import Mapping
10
+ from pathlib import Path
11
+ from typing import Any
12
+
13
+ import torch
14
+ from omegaconf import OmegaConf
15
+ from safetensors.torch import load_file
16
+
17
+ from graph_lib import get_graph
18
+ from model import SEDD
19
+ from noise_lib import get_noise
20
+
21
+
22
+ ARTIFACT_SCHEMA = "sedd_math_tool_hf_inference_v1"
23
+ _SHA256_RE = re.compile(r"[0-9a-f]{64}")
24
+ _CONFIG_KEYS = {
25
+ "artifact_format",
26
+ "tokens",
27
+ "graph",
28
+ "noise",
29
+ "sampling",
30
+ "model",
31
+ "tokenizer",
32
+ }
33
+ _MODEL_KEYS = {
34
+ "name",
35
+ "type",
36
+ "hidden_size",
37
+ "cond_dim",
38
+ "length",
39
+ "n_blocks",
40
+ "n_heads",
41
+ "scale_by_sigma",
42
+ "dropout",
43
+ }
44
+
45
+
46
+ def sha256_file(path: Path) -> str:
47
+ digest = hashlib.sha256()
48
+ with path.open("rb") as handle:
49
+ for chunk in iter(lambda: handle.read(8 * 1024 * 1024), b""):
50
+ digest.update(chunk)
51
+ return digest.hexdigest()
52
+
53
+
54
+ def _exact_keys(value: Any, keys: set[str], name: str) -> Mapping[str, Any]:
55
+ if not isinstance(value, Mapping) or set(value) != keys:
56
+ raise ValueError(f"Unexpected {name} fields")
57
+ return value
58
+
59
+
60
+ def _positive_int(value: Any, name: str) -> int:
61
+ if type(value) is not int or value <= 0:
62
+ raise ValueError(f"{name} must be a positive integer")
63
+ return value
64
+
65
+
66
+ def _finite_number(value: Any, name: str) -> float:
67
+ if isinstance(value, bool) or not isinstance(value, (int, float)):
68
+ raise ValueError(f"{name} must be numeric")
69
+ result = float(value)
70
+ if not math.isfinite(result):
71
+ raise ValueError(f"{name} must be finite")
72
+ return result
73
+
74
+
75
+ def validate_artifact_config(value: Any) -> dict[str, Any]:
76
+ config = _exact_keys(value, _CONFIG_KEYS, "config")
77
+ if config["artifact_format"] != ARTIFACT_SCHEMA:
78
+ raise ValueError("Config artifact schema does not match the loader")
79
+ _positive_int(config["tokens"], "tokens")
80
+
81
+ graph = _exact_keys(config["graph"], {"type"}, "graph config")
82
+ if graph["type"] != "absorb":
83
+ raise ValueError("Only the audited absorbing graph is supported")
84
+
85
+ noise = _exact_keys(
86
+ config["noise"], {"type", "sigma_min", "sigma_max"}, "noise config"
87
+ )
88
+ if noise["type"] != "loglinear":
89
+ raise ValueError("Only the audited loglinear noise is supported")
90
+ sigma_min = _finite_number(noise["sigma_min"], "noise.sigma_min")
91
+ sigma_max = _finite_number(noise["sigma_max"], "noise.sigma_max")
92
+ if sigma_min <= 0 or sigma_max <= sigma_min:
93
+ raise ValueError("Invalid noise sigma range")
94
+
95
+ sampling = _exact_keys(
96
+ config["sampling"],
97
+ {"predictor", "steps", "noise_removal", "eps"},
98
+ "sampling config",
99
+ )
100
+ if sampling["predictor"] != "euler":
101
+ raise ValueError("Only the audited Euler predictor is supported")
102
+ _positive_int(sampling["steps"], "sampling.steps")
103
+ if type(sampling["noise_removal"]) is not bool:
104
+ raise ValueError("sampling.noise_removal must be boolean")
105
+ if _finite_number(sampling["eps"], "sampling.eps") <= 0:
106
+ raise ValueError("sampling.eps must be positive")
107
+
108
+ model = _exact_keys(config["model"], _MODEL_KEYS, "model config")
109
+ if model["type"] != "ddit" or not isinstance(model["name"], str):
110
+ raise ValueError("Unexpected model family")
111
+ for field in ("hidden_size", "cond_dim", "length", "n_blocks", "n_heads"):
112
+ _positive_int(model[field], f"model.{field}")
113
+ if model["hidden_size"] % model["n_heads"]:
114
+ raise ValueError("model.hidden_size must be divisible by model.n_heads")
115
+ if type(model["scale_by_sigma"]) is not bool:
116
+ raise ValueError("model.scale_by_sigma must be boolean")
117
+ dropout = _finite_number(model["dropout"], "model.dropout")
118
+ if not 0 <= dropout < 1:
119
+ raise ValueError("model.dropout must be in [0, 1)")
120
+
121
+ tokenizer = _exact_keys(
122
+ config["tokenizer"],
123
+ {"identifier", "vocab_sha256", "add_special_tokens"},
124
+ "tokenizer config",
125
+ )
126
+ if not isinstance(tokenizer["identifier"], str) or not tokenizer["identifier"]:
127
+ raise ValueError("tokenizer.identifier must be a non-empty string")
128
+ if not isinstance(tokenizer["vocab_sha256"], str) or not _SHA256_RE.fullmatch(
129
+ tokenizer["vocab_sha256"]
130
+ ):
131
+ raise ValueError("tokenizer.vocab_sha256 must be a SHA-256 digest")
132
+ if tokenizer["add_special_tokens"] is not False:
133
+ raise ValueError("The audited tokenizer does not add special tokens")
134
+ return dict(config)
135
+
136
+
137
+ def _load_metadata(model_dir: Path) -> dict[str, Any]:
138
+ path = model_dir / "inference_metadata.json"
139
+ value = json.loads(path.read_text(encoding="utf-8"))
140
+ if not isinstance(value, dict) or value.get("schema_version") != ARTIFACT_SCHEMA:
141
+ raise ValueError("Unsupported Hugging Face SEDD artifact metadata")
142
+ return value
143
+
144
+
145
+ def _record_path(
146
+ model_dir: Path,
147
+ record: Mapping[str, Any],
148
+ expected_name: str,
149
+ *,
150
+ verify: bool,
151
+ ) -> Path:
152
+ if record.get("file") != expected_name:
153
+ raise ValueError(f"Artifact record must name {expected_name}")
154
+ expected_sha = record.get("sha256")
155
+ if not isinstance(expected_sha, str) or not _SHA256_RE.fullmatch(expected_sha):
156
+ raise ValueError(f"Invalid SHA-256 record for {expected_name}")
157
+ expected_size = record.get("size_bytes")
158
+ if type(expected_size) is not int or expected_size < 0:
159
+ raise ValueError(f"Invalid size record for {expected_name}")
160
+
161
+ path = model_dir / expected_name
162
+ if not path.is_file():
163
+ raise FileNotFoundError(path)
164
+ actual_size = path.stat().st_size
165
+ if actual_size != expected_size:
166
+ raise RuntimeError(
167
+ f"Size mismatch for {expected_name}: {actual_size} != {expected_size}"
168
+ )
169
+ if verify:
170
+ actual_sha = sha256_file(path)
171
+ if actual_sha != expected_sha:
172
+ raise RuntimeError(f"SHA-256 mismatch for {expected_name}: {actual_sha}")
173
+ return path
174
+
175
+
176
+ def _load_state(
177
+ module: torch.nn.Module,
178
+ path: Path,
179
+ record: Mapping[str, Any],
180
+ name: str,
181
+ ) -> None:
182
+ if record.get("dtype") != "float32":
183
+ raise ValueError(f"{name} metadata must declare float32")
184
+ expected_count = record.get("tensor_count")
185
+ if type(expected_count) is not int or expected_count <= 0:
186
+ raise ValueError(f"Invalid tensor count for {name}")
187
+
188
+ state = load_file(path, device="cpu")
189
+ expected = module.state_dict()
190
+ if len(state) != expected_count:
191
+ raise ValueError(f"Tensor count mismatch for {name}")
192
+ if set(state) != set(expected):
193
+ raise ValueError(f"State keys do not match for {name}")
194
+ for key, tensor in state.items():
195
+ reference = expected[key]
196
+ if tensor.shape != reference.shape:
197
+ raise ValueError(f"Shape mismatch for {name}.{key}")
198
+ if tensor.dtype != torch.float32 or tensor.dtype != reference.dtype:
199
+ raise ValueError(f"Dtype mismatch for {name}.{key}")
200
+ if not bool(torch.isfinite(tensor).all().item()):
201
+ raise ValueError(f"Non-finite tensor in {name}.{key}")
202
+ module.load_state_dict(state, strict=True)
203
+
204
+
205
+ def load_hf_sedd_model(
206
+ model_dir: str | Path,
207
+ device: str | torch.device = "cuda",
208
+ *,
209
+ verify: bool = True,
210
+ ) -> tuple[SEDD, Any, torch.nn.Module, Any, dict[str, Any]]:
211
+ """Load the complete online weights without a base or training checkpoint.
212
+
213
+ Returns ``(model, graph, noise, config, metadata)``. SHA-256 verification is
214
+ enabled by default; disabling it still enforces filenames, sizes, schemas,
215
+ tensor keys, shapes, dtypes, and finite values.
216
+ """
217
+
218
+ root = Path(model_dir).resolve()
219
+ metadata = _load_metadata(root)
220
+ weights = metadata.get("weights")
221
+ if not isinstance(weights, Mapping) or metadata.get("weights_variant") != "online":
222
+ raise ValueError("Artifact must contain the audited online weight variant")
223
+
224
+ model_record = weights.get("model")
225
+ noise_record = weights.get("noise")
226
+ config_record = metadata.get("config")
227
+ if not all(
228
+ isinstance(record, Mapping)
229
+ for record in (model_record, noise_record, config_record)
230
+ ):
231
+ raise ValueError("Artifact file records are incomplete")
232
+
233
+ model_path = _record_path(root, model_record, "model.safetensors", verify=verify)
234
+ noise_path = _record_path(root, noise_record, "noise.safetensors", verify=verify)
235
+ config_path = _record_path(root, config_record, "config.json", verify=verify)
236
+ config_value = validate_artifact_config(
237
+ json.loads(config_path.read_text(encoding="utf-8"))
238
+ )
239
+ config = OmegaConf.create(config_value)
240
+
241
+ model = SEDD(config)
242
+ _load_state(model, model_path, model_record, "model")
243
+ noise = get_noise(config)
244
+ _load_state(noise, noise_path, noise_record, "noise")
245
+
246
+ target = torch.device(device)
247
+ model = model.to(target).eval()
248
+ noise = noise.to(target).eval()
249
+ graph = get_graph(config, target)
250
+ return model, graph, noise, config, metadata
251
+
252
+
253
+ __all__ = [
254
+ "ARTIFACT_SCHEMA",
255
+ "load_hf_sedd_model",
256
+ "sha256_file",
257
+ "validate_artifact_config",
258
+ ]
inference_metadata.json ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "adaptation": "full",
3
+ "config": {
4
+ "file": "config.json",
5
+ "sha256": "e66555794ccb143ffe4654f10099238ab58465b56bb5fcabc6008a1b672b1e0c",
6
+ "size_bytes": 693
7
+ },
8
+ "evaluation": {
9
+ "file": "metrics.json",
10
+ "sha256": "f315e172dc6f117b973e26137ee4a3b6396888f2586eb8bfd1d298fc81132f4b",
11
+ "size_bytes": 1409,
12
+ "source_sha256": "f315e172dc6f117b973e26137ee4a3b6396888f2586eb8bfd1d298fc81132f4b"
13
+ },
14
+ "global_step": 600,
15
+ "model_state_elements": 424477042,
16
+ "parameter_count": 424477010,
17
+ "records_seen": 96000,
18
+ "schema_version": "sedd_math_tool_hf_inference_v1",
19
+ "source": {
20
+ "base_config_sha256": "f77926529f6ee5b913981775ebd2f8560c271341ad6dc67a0eab4c56eb032ec5",
21
+ "base_model": "louaaron/sedd-medium",
22
+ "base_model_sha256": "d93bb0dd1013295a4865848ea546ee3763a5be036cf55ea407e898c0a7a82a33",
23
+ "base_revision": "ce71a3c6178b50e899c8be1a1a4c13130308e54f",
24
+ "code_commit": "9b26b8980b298ce5cf08013320354ad4141796c1",
25
+ "code_repository": "https://github.com/Jrffy666/SEDD",
26
+ "training_checkpoint_included": false,
27
+ "training_checkpoint_sha256": "020f76c434acb7652adcf0bc09f26c4605a00e7fe4462b6f71cea7f91438ebd5",
28
+ "training_checkpoint_size_bytes": 6792032589
29
+ },
30
+ "trainable_parameter_count": 424477011,
31
+ "weights": {
32
+ "model": {
33
+ "dtype": "float32",
34
+ "file": "model.safetensors",
35
+ "sha256": "f3ee746f5ab56f8549592eca81bb33198b66ff16940cd6959e16943a5b06ee4a",
36
+ "size_bytes": 1697932808,
37
+ "tensor_count": 251
38
+ },
39
+ "noise": {
40
+ "dtype": "float32",
41
+ "file": "noise.safetensors",
42
+ "sha256": "7559b29efa5cf3ab3ae472de3985faa543ece81f74eec9e1ba43a88265587261",
43
+ "size_bytes": 100,
44
+ "tensor_count": 1
45
+ }
46
+ },
47
+ "weights_variant": "online"
48
+ }
metrics.json ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "checkpoint": {
3
+ "adaptation": "full",
4
+ "global_step": 600,
5
+ "records_seen": 96000,
6
+ "sha256": "020f76c434acb7652adcf0bc09f26c4605a00e7fe4462b6f71cea7f91438ebd5",
7
+ "weights": "online"
8
+ },
9
+ "dataset_fingerprint": "d19f485febc970c3bd61b0ed4259c7229658c3e724c35817ee3806f66e614663",
10
+ "metrics": {
11
+ "completed": 444,
12
+ "completion_rate": 0.8671875,
13
+ "correct": 237,
14
+ "episodes": 512,
15
+ "final_answer_accuracy": 0.462890625,
16
+ "mean_calls": 6.55078125,
17
+ "oracle_action_exact_rate": 0.8631660631143301,
18
+ "oracle_plan_exact": 230,
19
+ "oracle_plan_exact_rate": 0.44921875,
20
+ "syntax_valid_turn_rate": 0.9824107604759441
21
+ },
22
+ "previously_unobserved_suffix": {
23
+ "correct": 208,
24
+ "episodes": 448,
25
+ "final_answer_accuracy": 0.4642857142857143,
26
+ "meaning": "Episodes 64..511 were not used for staged observation before the final sealed run.",
27
+ "start_index": 64
28
+ },
29
+ "report_scope": "aggregate_only; sealed prompts and trajectories withheld",
30
+ "sampling": {
31
+ "base_seed": 710001,
32
+ "sequence_length": 256,
33
+ "steps": 64
34
+ },
35
+ "schema_version": "sedd_public_aggregate_evaluation_v1",
36
+ "selection_range": {
37
+ "start": 0,
38
+ "stop": 512
39
+ },
40
+ "source_report": {
41
+ "included_in_public_repository": false,
42
+ "sha256": "7e434e1ecc607540a94d39239ae689dbc88374c23dcfc16f579225d30e6d54e6",
43
+ "size_bytes": 2953834
44
+ },
45
+ "split": "extrapolate"
46
+ }
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f3ee746f5ab56f8549592eca81bb33198b66ff16940cd6959e16943a5b06ee4a
3
+ size 1697932808
model/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ from .transformer import SEDD
model/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (221 Bytes). View file
 
model/__pycache__/fused_add_dropout_scale.cpython-311.pyc ADDED
Binary file (3.15 kB). View file
 
model/__pycache__/rotary.cpython-311.pyc ADDED
Binary file (3.56 kB). View file
 
model/__pycache__/transformer.cpython-311.pyc ADDED
Binary file (18.3 kB). View file
 
model/fused_add_dropout_scale.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn.functional as F
3
+ from typing import Optional
4
+ from torch import Tensor
5
+
6
+ # flags required to enable jit fusion kernels
7
+ torch._C._jit_set_profiling_mode(False)
8
+ torch._C._jit_set_profiling_executor(False)
9
+ torch._C._jit_override_can_fuse_on_cpu(True)
10
+ torch._C._jit_override_can_fuse_on_gpu(True)
11
+
12
+
13
+ def bias_dropout_add_scale(
14
+ x: Tensor, bias: Optional[Tensor], scale: Tensor, residual: Optional[Tensor], prob: float, training: bool
15
+ ) -> Tensor:
16
+ if bias is not None:
17
+ out = scale * F.dropout(x + bias, p=prob, training=training)
18
+ else:
19
+ out = scale * F.dropout(x, p=prob, training=training)
20
+
21
+ if residual is not None:
22
+ out = residual + out
23
+ return out
24
+
25
+
26
+ def get_bias_dropout_add_scale(training):
27
+ def _bias_dropout_add(x, bias, scale, residual, prob):
28
+ return bias_dropout_add_scale(x, bias, scale, residual, prob, training)
29
+
30
+ return _bias_dropout_add
31
+
32
+
33
+ def modulate(x: Tensor, shift: Tensor, scale: Tensor) -> Tensor:
34
+ return x * (1 + scale) + shift
35
+
36
+
37
+ @torch.jit.script
38
+ def bias_dropout_add_scale_fused_train(
39
+ x: Tensor, bias: Optional[Tensor], scale: Tensor, residual: Optional[Tensor], prob: float
40
+ ) -> Tensor:
41
+ return bias_dropout_add_scale(x, bias, scale, residual, prob, True)
42
+
43
+
44
+ @torch.jit.script
45
+ def bias_dropout_add_scale_fused_inference(
46
+ x: Tensor, bias: Optional[Tensor], scale: Tensor, residual: Optional[Tensor], prob: float
47
+ ) -> Tensor:
48
+ return bias_dropout_add_scale(x, bias, scale, residual, prob, False)
49
+
50
+ @torch.jit.script
51
+ def modulate_fused(x: Tensor, shift: Tensor, scale: Tensor) -> Tensor:
52
+ return modulate(x, shift, scale)
model/rotary.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from torch import nn
3
+
4
+
5
+ class Rotary(torch.nn.Module):
6
+ def __init__(self, dim, base=10_000):
7
+ super().__init__()
8
+ inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2).float() / dim))
9
+ self.register_buffer("inv_freq", inv_freq)
10
+ self.seq_len_cached = None
11
+ self.cos_cached = None
12
+ self.sin_cached = None
13
+
14
+ def forward(self, x, seq_dim=1):
15
+ seq_len = x.shape[seq_dim]
16
+ if seq_len != self.seq_len_cached:
17
+ self.seq_len_cached = seq_len
18
+ t = torch.arange(x.shape[seq_dim], device=x.device).type_as(self.inv_freq)
19
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq.clone())
20
+ emb = torch.cat((freqs, freqs), dim=-1).to(x.device)
21
+ # dims are: batch, seq_len, qkv, head, dim
22
+ self.cos_cached = emb.cos()[None, :, None, None, :].repeat(1,1,3,1,1)
23
+ self.sin_cached = emb.sin()[None, :, None, None, :].repeat(1,1,3,1,1)
24
+ # This makes the transformation on v an identity.
25
+ self.cos_cached[:,:,2,:,:].fill_(1.)
26
+ self.sin_cached[:,:,2,:,:].fill_(0.)
27
+
28
+ return self.cos_cached, self.sin_cached
29
+
30
+
31
+ def rotate_half(x):
32
+ half = x.size(-1) // 2
33
+ x1, x2 = x[..., :half], x[..., half:]
34
+ return torch.cat(
35
+ (-x2, x1), dim=-1
36
+ )
37
+
38
+
39
+ def _apply_rotary_pos_emb_torch(qkv, cos, sin):
40
+ return (qkv * cos) + (rotate_half(qkv) * sin)
41
+
42
+
43
+ def apply_rotary_pos_emb(qkv, cos, sin):
44
+ return _apply_rotary_pos_emb_torch(qkv, cos, sin)
model/transformer.py ADDED
@@ -0,0 +1,279 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import torch.nn.functional as F
4
+ import numpy as np
5
+ import math
6
+
7
+ from einops import rearrange
8
+ # from flash_attn.ops.fused_dense import FusedMLP, FusedDense
9
+ from huggingface_hub import PyTorchModelHubMixin
10
+ from omegaconf import OmegaConf
11
+
12
+ from . import rotary
13
+ from .fused_add_dropout_scale import (
14
+ bias_dropout_add_scale_fused_train,
15
+ bias_dropout_add_scale_fused_inference,
16
+ get_bias_dropout_add_scale,
17
+ modulate_fused,
18
+ )
19
+
20
+
21
+ def modulate(x, shift, scale):
22
+ return x * (1 + scale.unsqueeze(1)) + shift.unsqueeze(1)
23
+
24
+
25
+
26
+ #################################################################################
27
+ # Layers #
28
+ #################################################################################
29
+ class LayerNorm(nn.Module):
30
+ def __init__(self, dim):
31
+ super().__init__()
32
+ self.weight = nn.Parameter(torch.ones([dim]))
33
+ self.dim = dim
34
+ def forward(self, x):
35
+ with torch.amp.autocast("cuda", enabled=False):
36
+ x = F.layer_norm(x.float(), [self.dim])
37
+ return x * self.weight[None,None,:]
38
+
39
+
40
+ def residual_linear(x, W, x_skip, residual_scale):
41
+ """x_skip + residual_scale * W @ x"""
42
+ dim_out, dim_in = W.shape[0], W.shape[1]
43
+ return torch.addmm(
44
+ x_skip.view(-1, dim_out),
45
+ x.view(-1, dim_in),
46
+ W.T,
47
+ alpha=residual_scale
48
+ ).view(*x.shape[:-1], dim_out)
49
+
50
+
51
+ #################################################################################
52
+ # Embedding Layers for Timesteps and Class Labels #
53
+ #################################################################################
54
+
55
+ class TimestepEmbedder(nn.Module):
56
+ """
57
+ Embeds scalar timesteps into vector representations.
58
+ """
59
+ def __init__(self, hidden_size, frequency_embedding_size=256, silu=True):
60
+ super().__init__()
61
+ self.mlp = nn.Sequential(
62
+ nn.Linear(frequency_embedding_size, hidden_size, bias=True),
63
+ nn.SiLU(),
64
+ nn.Linear(hidden_size, hidden_size, bias=True),
65
+ )
66
+ self.frequency_embedding_size = frequency_embedding_size
67
+
68
+
69
+ @staticmethod
70
+ def timestep_embedding(t, dim, max_period=10000):
71
+ """
72
+ Create sinusoidal timestep embeddings.
73
+ :param t: a 1-D Tensor of N indices, one per batch element.
74
+ These may be fractional.
75
+ :param dim: the dimension of the output.
76
+ :param max_period: controls the minimum frequency of the embeddings.
77
+ :return: an (N, D) Tensor of positional embeddings.
78
+ """
79
+ # https://github.com/openai/glide-text2im/blob/main/glide_text2im/nn.py
80
+ half = dim // 2
81
+ freqs = torch.exp(
82
+ -math.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32) / half
83
+ ).to(device=t.device)
84
+ args = t[:, None].float() * freqs[None]
85
+ embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1)
86
+ if dim % 2:
87
+ embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1)
88
+ return embedding
89
+
90
+ def forward(self, t):
91
+ t_freq = self.timestep_embedding(t, self.frequency_embedding_size)
92
+ t_emb = self.mlp(t_freq)
93
+ return t_emb
94
+
95
+
96
+ class LabelEmbedder(nn.Module):
97
+ """
98
+ Embeds class labels into vector representations. Also handles label dropout for classifier-free guidance.
99
+ """
100
+ def __init__(self, num_classes, cond_size):
101
+ super().__init__()
102
+ self.embedding_table = nn.Embedding(num_classes + 1, cond_size)
103
+ self.num_classes = num_classes
104
+
105
+ # TODO think of initializing with 0.02 std deviation like in original DiT paper
106
+
107
+ def forward(self, labels):
108
+ embeddings = self.embedding_table(labels)
109
+ return embeddings
110
+
111
+
112
+ #################################################################################
113
+ # Core Model #
114
+ #################################################################################
115
+
116
+
117
+ class DDiTBlock(nn.Module):
118
+
119
+ def __init__(self, dim, n_heads, cond_dim, mlp_ratio=4, dropout=0.1):
120
+ super().__init__()
121
+ self.n_heads = n_heads
122
+
123
+ self.norm1 = LayerNorm(dim)
124
+ self.attn_qkv = nn.Linear(dim, 3 * dim, bias=False)
125
+ self.attn_out = nn.Linear(dim, dim, bias=False)
126
+ self.dropout1 = nn.Dropout(dropout)
127
+
128
+ self.norm2 = LayerNorm(dim)
129
+ self.mlp = nn.Sequential(
130
+ nn.Linear(dim, mlp_ratio * dim, bias=True),
131
+ nn.GELU(approximate="tanh"),
132
+ nn.Linear(mlp_ratio * dim, dim, bias=True)
133
+ )
134
+ self.dropout2 = nn.Dropout(dropout)
135
+
136
+ self.dropout = dropout
137
+
138
+
139
+ self.adaLN_modulation = nn.Linear(cond_dim, 6 * dim, bias=True)
140
+ self.adaLN_modulation.weight.data.zero_()
141
+ self.adaLN_modulation.bias.data.zero_()
142
+
143
+
144
+ def _get_bias_dropout_scale(self):
145
+ return (
146
+ bias_dropout_add_scale_fused_train
147
+ if self.training
148
+ else bias_dropout_add_scale_fused_inference
149
+ )
150
+
151
+
152
+ def forward(self, x, rotary_cos_sin, c, seqlens=None):
153
+ bias_dropout_scale_fn = self._get_bias_dropout_scale()
154
+
155
+ shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.adaLN_modulation(c)[:, None].chunk(6, dim=2)
156
+
157
+ # attention operation
158
+ x_skip = x
159
+ x = modulate_fused(self.norm1(x), shift_msa, scale_msa)
160
+ # dtype0 = x.dtype
161
+
162
+ qkv = self.attn_qkv(x)
163
+ qkv = rearrange(qkv, 'b s (three h d) -> b s three h d', three=3, h=self.n_heads)
164
+ with torch.amp.autocast("cuda", enabled=False):
165
+ cos, sin = rotary_cos_sin
166
+ qkv = rotary.apply_rotary_pos_emb(
167
+ qkv, cos.to(qkv.dtype), sin.to(qkv.dtype)
168
+ )
169
+ if seqlens is not None:
170
+ raise NotImplementedError(
171
+ "Variable-length attention is not used by SEDD's forward pass."
172
+ )
173
+
174
+ q, k, v = qkv.unbind(dim=2)
175
+ q = q.transpose(1, 2)
176
+ k = k.transpose(1, 2)
177
+ v = v.transpose(1, 2)
178
+ x = F.scaled_dot_product_attention(
179
+ q, k, v, dropout_p=0.0, is_causal=False
180
+ )
181
+ x = rearrange(x, 'b h s d -> b s (h d)')
182
+
183
+ x = bias_dropout_scale_fn(self.attn_out(x), None, gate_msa, x_skip, self.dropout)
184
+
185
+ # mlp operation
186
+ x = bias_dropout_scale_fn(self.mlp(modulate_fused(self.norm2(x), shift_mlp, scale_mlp)), None, gate_mlp, x, self.dropout)
187
+ return x
188
+
189
+
190
+
191
+ class EmbeddingLayer(nn.Module):
192
+ def __init__(self, dim, vocab_dim):
193
+ """
194
+ Mode arg: 0 -> use a learned layer, 1 -> use eigenvectors,
195
+ 2-> add in eigenvectors, 3 -> use pretrained embedding matrix
196
+ """
197
+ super().__init__()
198
+ self.embedding = nn.Parameter(torch.empty((vocab_dim, dim)))
199
+ torch.nn.init.kaiming_uniform_(self.embedding, a=math.sqrt(5))
200
+
201
+ def forward(self, x):
202
+ return self.embedding[x]
203
+
204
+
205
+ class DDitFinalLayer(nn.Module):
206
+ def __init__(self, hidden_size, out_channels, cond_dim):
207
+ super().__init__()
208
+ self.norm_final = LayerNorm(hidden_size)
209
+ self.linear = nn.Linear(hidden_size, out_channels)
210
+ self.linear.weight.data.zero_()
211
+ self.linear.bias.data.zero_()
212
+
213
+ self.adaLN_modulation = nn.Linear(cond_dim, 2 * hidden_size, bias=True)
214
+ self.adaLN_modulation.weight.data.zero_()
215
+ self.adaLN_modulation.bias.data.zero_()
216
+
217
+
218
+ def forward(self, x, c):
219
+ shift, scale = self.adaLN_modulation(c)[:, None].chunk(2, dim=2)
220
+ x = modulate_fused(self.norm_final(x), shift, scale)
221
+ x = self.linear(x)
222
+ return x
223
+
224
+
225
+ class SEDD(nn.Module, PyTorchModelHubMixin):
226
+ def __init__(self, config):
227
+ super().__init__()
228
+
229
+ # hack to make loading in configs easier
230
+ if type(config) == dict:
231
+ config = OmegaConf.create(config)
232
+
233
+ self.config = config
234
+
235
+ self.absorb = config.graph.type == "absorb"
236
+ vocab_size = config.tokens + (1 if self.absorb else 0)
237
+
238
+ self.vocab_embed = EmbeddingLayer(config.model.hidden_size, vocab_size)
239
+ self.sigma_map = TimestepEmbedder(config.model.cond_dim)
240
+ self.rotary_emb = rotary.Rotary(config.model.hidden_size // config.model.n_heads)
241
+
242
+ self.blocks = nn.ModuleList([
243
+ DDiTBlock(config.model.hidden_size, config.model.n_heads, config.model.cond_dim, dropout=config.model.dropout) for _ in range(config.model.n_blocks)
244
+ ])
245
+
246
+ self.output_layer = DDitFinalLayer(config.model.hidden_size, vocab_size, config.model.cond_dim)
247
+ self.scale_by_sigma = config.model.scale_by_sigma
248
+
249
+
250
+ def _get_bias_dropout_scale(self):
251
+ return (
252
+ bias_dropout_add_scale_fused_train
253
+ if self.training
254
+ else bias_dropout_add_scale_fused_inference
255
+ )
256
+
257
+
258
+ def forward(self, indices, sigma):
259
+
260
+ x = self.vocab_embed(indices)
261
+ c = F.silu(self.sigma_map(sigma))
262
+
263
+ rotary_cos_sin = self.rotary_emb(x)
264
+
265
+ with torch.amp.autocast("cuda", dtype=torch.bfloat16):
266
+ for i in range(len(self.blocks)):
267
+ x = self.blocks[i](x, rotary_cos_sin, c, seqlens=None)
268
+
269
+ x = self.output_layer(x, c)
270
+
271
+
272
+ if self.scale_by_sigma:
273
+ assert self.absorb, "Haven't configured this to work."
274
+ esigm1_log = torch.where(sigma < 0.5, torch.expm1(sigma), sigma.exp() - 1).log().to(x.dtype)[:, None, None]
275
+ x = x - esigm1_log - np.log(x.shape[-1] - 1)# this will be approximately averaged at 0
276
+
277
+ x = torch.scatter(x, -1, indices[..., None], torch.zeros_like(x[..., :1]))
278
+
279
+ return x
noise.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7559b29efa5cf3ab3ae472de3985faa543ece81f74eec9e1ba43a88265587261
3
+ size 100
noise_lib.py ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import abc
2
+ import torch
3
+ import torch.nn as nn
4
+ import numpy as np
5
+
6
+
7
+ def get_noise(config):
8
+ if config.noise.type == "geometric":
9
+ return GeometricNoise(config.noise.sigma_min, config.noise.sigma_max)
10
+ elif config.noise.type == "loglinear":
11
+ return LogLinearNoise()
12
+ else:
13
+ raise ValueError(f"{config.noise.type} is not a valid noise")
14
+
15
+
16
+ class Noise(abc.ABC, nn.Module):
17
+ """
18
+ Baseline forward method to get the total + rate of noise at a timestep
19
+ """
20
+ def forward(self, t):
21
+ return self.total_noise(t), self.rate_noise(t)
22
+
23
+ """
24
+ Assume time goes from 0 to 1
25
+ """
26
+ @abc.abstractmethod
27
+ def rate_noise(self, t):
28
+ """
29
+ Rate of change of noise ie g(t)
30
+ """
31
+ pass
32
+
33
+ @abc.abstractmethod
34
+ def total_noise(self, t):
35
+ """
36
+ Total noise ie \int_0^t g(t) dt + g(0)
37
+ """
38
+ pass
39
+
40
+
41
+ class GeometricNoise(Noise, nn.Module):
42
+ def __init__(self, sigma_min=1e-3, sigma_max=1, learnable=False):
43
+ super().__init__()
44
+ self.sigmas = 1.0 * torch.tensor([sigma_min, sigma_max])
45
+ if learnable:
46
+ self.sigmas = nn.Parameter(self.sigmas)
47
+ self.empty = nn.Parameter(torch.tensor(0.0))
48
+
49
+ def rate_noise(self, t):
50
+ return self.sigmas[0] ** (1 - t) * self.sigmas[1] ** t * (self.sigmas[1].log() - self.sigmas[0].log())
51
+
52
+ def total_noise(self, t):
53
+ return self.sigmas[0] ** (1 - t) * self.sigmas[1] ** t
54
+
55
+
56
+ class LogLinearNoise(Noise, nn.Module):
57
+ """
58
+ Log Linear noise schedule built so that 1 - 1/e^(n(t)) interpolates between 0 and ~1
59
+ when t goes from 0 to 1. Used for absorbing
60
+
61
+ Total noise is -log(1 - (1 - eps) * t), so the sigma will be (1 - eps) * t
62
+ """
63
+ def __init__(self, eps=1e-3):
64
+ super().__init__()
65
+ self.eps = eps
66
+ self.empty = nn.Parameter(torch.tensor(0.0))
67
+
68
+ def rate_noise(self, t):
69
+ return (1 - self.eps) / (1 - (1 - self.eps) * t)
70
+
71
+ def total_noise(self, t):
72
+ return -torch.log1p(-(1 - self.eps) * t)
73
+
requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ torch>=2.1
2
+ safetensors>=0.4.2
3
+ omegaconf>=2.3.0
4
+ numpy>=1.26
5
+ einops>=0.7
6
+ huggingface-hub>=0.21