pyqitnn 0.3.6__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
pyqitnn-0.3.6/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,4 @@
1
+ include README.md
2
+ include pyproject.toml
3
+ recursive-include csrc *.cu *.h
4
+ recursive-include src *.cpp
pyqitnn-0.3.6/PKG-INFO ADDED
@@ -0,0 +1,443 @@
1
+ Metadata-Version: 2.1
2
+ Name: pyqitnn
3
+ Version: 0.3.6
4
+ Summary: Quantum-inspired ternary neural network layers for PyTorch
5
+ License: Apache-2.0
6
+ Project-URL: Homepage, https://github.com/kaifczxc-lab/PyQITNN
7
+ Keywords: quantum,ternary,neural-network,pytorch,cuda
8
+ Classifier: Development Status :: 4 - Beta
9
+ Classifier: Intended Audience :: Science/Research
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Programming Language :: Python :: 3.10
12
+ Classifier: Programming Language :: Python :: 3.11
13
+ Classifier: Programming Language :: Python :: 3.12
14
+ Classifier: Programming Language :: Python :: 3.13
15
+ Classifier: Programming Language :: C++
16
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
17
+ Classifier: Operating System :: Microsoft :: Windows
18
+ Classifier: Operating System :: POSIX :: Linux
19
+ Classifier: Environment :: GPU :: NVIDIA CUDA
20
+ Requires-Python: >=3.10
21
+ Description-Content-Type: text/markdown
22
+ License-File: LICENSE
23
+ Provides-Extra: tokenizers
24
+ Requires-Dist: tokenizers<0.23,>=0.22; extra == "tokenizers"
25
+
26
+ # PyQITNN
27
+
28
+ A PyTorch library implementing quantum-inspired ternary neural network layers.
29
+ Runs on standard NVIDIA GPUs; no quantum hardware is required.
30
+
31
+ ```python
32
+ import torch
33
+ import pyqitnn
34
+
35
+ model = pyqitnn.QITNNSimplexTransformerLM(
36
+ vocab_size=256,
37
+ dim=64,
38
+ ffn_dim=128,
39
+ seq_len=128,
40
+ layers=2,
41
+ precision_mode="fp32",
42
+ device="cuda:0",
43
+ )
44
+ tokens = torch.randint(0, 256, (2, 128), device="cuda:0")
45
+ targets = torch.randint(0, 256, (2, 128), device="cuda:0")
46
+ logits, loss = model(tokens, targets=targets)
47
+ loss.backward()
48
+ ```
49
+
50
+ ---
51
+
52
+ ## What this is
53
+
54
+ Every linear projection stores three amplitude vectors `(a_neg, a_zero, a_pos)` instead of
55
+ one weight matrix. A Born-rule normalization converts amplitudes to ternary probabilities
56
+ `(P-, P0, P+)`. The result propagates through the network as a full 2D centered simplex
57
+ state `[x | y]`, not a collapsed scalar.
58
+
59
+ This gives the network two independent degrees of freedom per output coordinate - the minimal
60
+ complete representation of a ternary probability state.
61
+
62
+ These are classical amplitudes computed on a GPU. The "quantum-inspired" part is the geometry
63
+ and the normalization rule, not the hardware.
64
+
65
+ ---
66
+
67
+ ## Installation
68
+
69
+ ### Prerequisites
70
+
71
+ - NVIDIA GPU with CUDA support
72
+ - Python 3.10+ at the source level
73
+ - PyTorch 2.0+ with CUDA support
74
+ - Local CUDA toolkit when building from source
75
+
76
+ ### Current tested setup
77
+
78
+ - Windows 11 x86_64
79
+ - Python 3.13
80
+ - PyTorch 2.10.0+cu126
81
+ - Local CUDA toolkit 13.1
82
+
83
+ The package contains a compiled CUDA extension. Prebuilt wheels are platform- and
84
+ Python-version-specific. If no wheel matches your environment, build from source inside
85
+ a CUDA-enabled PyTorch environment.
86
+
87
+ ### Install
88
+
89
+ Install a CUDA-enabled PyTorch build first. Example for CUDA 12.6:
90
+
91
+ ```bash
92
+ pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu126
93
+ ```
94
+
95
+ Then install PyQITNN without allowing pip to replace your existing Torch build:
96
+
97
+ ```bash
98
+ pip install pyqitnn --no-deps
99
+ ```
100
+
101
+ If you want optional BPE/subword tokenizer support:
102
+
103
+ ```bash
104
+ pip install pyqitnn[tokenizers] --no-deps
105
+ ```
106
+
107
+ ### Verify
108
+
109
+ ```python
110
+ import pyqitnn
111
+
112
+ status = pyqitnn.bridge_status()
113
+ print(pyqitnn.__version__) # e.g. 0.3.6
114
+ print(status["native_found"]) # True
115
+ print(status["native_loadable"]) # True
116
+ ```
117
+
118
+ ---
119
+
120
+ ## Quickstart
121
+
122
+ ### Single QTS layer
123
+
124
+ ```python
125
+ import torch
126
+ import pyqitnn
127
+
128
+ layer = pyqitnn.QITNNLinear(in_dim=64, out_dim=32, device="cuda:0")
129
+
130
+ x = torch.randn(4, 64, device="cuda:0")
131
+ out = layer(x) # shape: [4, 64] -> packed [x | y] simplex state
132
+ print(out.shape) # torch.Size([4, 64])
133
+ ```
134
+
135
+ ### Full transformer
136
+
137
+ ```python
138
+ import torch
139
+ import pyqitnn
140
+
141
+ model = pyqitnn.QITNNSimplexTransformerLM(
142
+ vocab_size=256, # byte-level
143
+ dim=64, # logical feature width
144
+ ffn_dim=128, # FFN intermediate width
145
+ seq_len=128, # max sequence length
146
+ layers=2, # transformer blocks
147
+ precision_mode="fp32", # explicit trusted baseline
148
+ device="cuda:0",
149
+ )
150
+
151
+ tokens = torch.randint(0, 256, (2, 128), device="cuda:0")
152
+ targets = torch.randint(0, 256, (2, 128), device="cuda:0")
153
+
154
+ logits, loss = model(tokens, targets=targets)
155
+ loss.backward()
156
+ ```
157
+
158
+ ### Training loop
159
+
160
+ ```python
161
+ import torch
162
+
163
+ opt = torch.optim.AdamW(model.parameters(), lr=3e-4)
164
+
165
+ for step in range(1000):
166
+ opt.zero_grad(set_to_none=True)
167
+ _, loss = model(tokens, targets=targets)
168
+ loss.backward()
169
+ opt.step()
170
+
171
+ # Entropy-floor prior. Call only after optimizer.step().
172
+ model.apply_qitnn_prior(
173
+ step_qk=5e-5,
174
+ step_vo=5e-5,
175
+ step_ff=5e-5,
176
+ entropy_floor=1.0840643,
177
+ )
178
+ ```
179
+
180
+ ### Mixed precision toggle
181
+
182
+ Core `pyqitnn` modules stay on dense `fp32` unless you opt in explicitly.
183
+
184
+ ```python
185
+ model = pyqitnn.QITNNSimplexTransformerLM(
186
+ vocab_size=256,
187
+ dim=64,
188
+ ffn_dim=128,
189
+ seq_len=128,
190
+ layers=2,
191
+ precision_mode="fp32",
192
+ device="cuda:0",
193
+ )
194
+ ```
195
+
196
+ Set `precision_mode="qts_fp32_rest_bf16"` to enable the conservative mixed path:
197
+
198
+ - visible activations use CUDA autocast (`bf16`)
199
+ - the native extension accepts `bf16/fp16` activations directly; it no longer relies on Python-side `float32` staging for mixed mode
200
+ - QITNN master weights stay in `fp32`
201
+ - sensitive math stays in `fp32`: Born normalization, backnorm, entropy/prior, and the attention softmax path
202
+ - training script / CLI: use `TrainConfig(precision_mode="qts_fp32_rest_bf16")` or `--precision-mode qts_fp32_rest_bf16`
203
+ - to force the trusted baseline explicitly from CLI, use `TrainConfig(precision_mode="fp32")`, `--precision-mode fp32`, or legacy `--no-mixed-precision`
204
+ - legacy compatibility still exists: `mixed_precision=True` maps to `qts_fp32_rest_bf16`
205
+
206
+ `BasicQITNN_Transformer.py` currently ships with `TrainConfig.precision_mode="qts_fp32_rest_bf16"` as its standalone trainer default. The lower-level `pyqitnn` modules still default to trusted `fp32` if you omit both `precision_mode` and legacy `mixed_precision`.
207
+
208
+ ### Generation
209
+
210
+ ```python
211
+ import torch
212
+
213
+ prompt = torch.tensor([[72, 101, 108, 108, 111]], device="cuda:0") # "Hello"
214
+ output = model.generate(prompt, max_new_tokens=64, temperature=0.7, top_k=12)
215
+
216
+ text = bytes(output[0].cpu().tolist()).decode("utf-8", errors="replace")
217
+ print(text)
218
+ ```
219
+
220
+ ### Tokenizer Modes
221
+
222
+ PyQITNN's QTS math is tokenizer-agnostic. Switching from byte tokens to BPE/subword
223
+ tokens does **not** change `forward3`, `backnorm3`, `centered_simplex`, `attention2`,
224
+ the 2D simplex state, or the ternary/Born-rule parameterization. It only changes
225
+ how raw text is mapped to token ids and what `vocab_size` the embedding/head use.
226
+
227
+ - `byte`: built in, fixed `vocab_size=256`, no extra dependency
228
+ - `bpe`: optional, uses HuggingFace `tokenizers`
229
+
230
+ ```python
231
+ import pyqitnn
232
+
233
+ bpe = pyqitnn.train_bpe_tokenizer(
234
+ ["hello simplex transformer", "born rule ternary attention"],
235
+ vocab_size=320,
236
+ min_frequency=1,
237
+ )
238
+
239
+ model = pyqitnn.QITNNSimplexTransformerLM(
240
+ vocab_size=bpe.vocab_size,
241
+ dim=64,
242
+ ffn_dim=128,
243
+ seq_len=128,
244
+ layers=2,
245
+ precision_mode="fp32",
246
+ device="cuda:0",
247
+ )
248
+ ```
249
+
250
+ ### Trainer data formats
251
+
252
+ The training script accepts plain text as well as structured JSON corpora.
253
+
254
+ - `text`: raw file contents
255
+ - `json`: parse JSON and extract text fields
256
+ - `jsonl` / `ndjson`: parse one JSON record per line
257
+ - `auto`: use file extension to choose between text and JSON parsing
258
+
259
+ For JSON inputs, the trainer can either collect all string leaves recursively or prefer
260
+ specific fields such as `text,content`.
261
+
262
+ ---
263
+
264
+ ## Architecture Overview
265
+
266
+ ```text
267
+ tokens -> embedding + pos_emb -> [x | y]
268
+ |
269
+ +---------+---------+
270
+ | QITNNSimplexBlock | x N layers
271
+ | |
272
+ | LN -> Q,K,V (QTS)|
273
+ | -> attention2 |
274
+ | -> O (QTS) |
275
+ | + residual |
276
+ | |
277
+ | LN -> ff1 (QTS) |
278
+ | -> gelu(x) | y |
279
+ | -> ff2 (QTS) |
280
+ | + residual |
281
+ +---------+---------+
282
+ |
283
+ final LN -> head -> logits
284
+ ```
285
+
286
+ Every QTS projection replaces a standard `nn.Linear` with three amplitude matrices and
287
+ Born-rule normalization. The hidden state is always packed as `[x | y]`, where `x` is the
288
+ polarity channel and `y` is the centered zero-state channel.
289
+
290
+ ---
291
+
292
+ ## Core Math
293
+
294
+ Each QTS projection computes:
295
+
296
+ ```text
297
+ C_neg = input @ A_neg
298
+ C_zero = input @ A_zero
299
+ C_pos = input @ A_pos
300
+
301
+ Z = C_neg^2 + C_zero^2 + C_pos^2
302
+
303
+ u = (C_pos^2 - C_neg^2) / Z # polarity, range [-1, +1]
304
+ v = C_zero^2 / Z # zero-state probability, range [0, 1]
305
+ ```
306
+
307
+ Then the centered simplex transform maps `(u, v)` to `(x, y)`:
308
+
309
+ ```text
310
+ x = u
311
+ y = sqrt(3) * v - 1/sqrt(3)
312
+ ```
313
+
314
+ The three pure qutrit states become vertices of an equilateral triangle:
315
+
316
+ | State | (u, v) | (x, y) |
317
+ |--------|---------|------------------|
318
+ | \|-1\> | (-1, 0) | (-1, -1/sqrt(3)) |
319
+ | \|0\> | (0, 1) | (0, 2/sqrt(3)) |
320
+ | \|+1\> | (1, 0) | (1, -1/sqrt(3)) |
321
+
322
+ Full math derivations are in the [reference](docs/reference.md).
323
+
324
+ ---
325
+
326
+ ## Stability And Training Notes
327
+
328
+ There are three separate stabilization mechanisms:
329
+
330
+ ### 1. `ent_lambda`
331
+
332
+ Adds entropy pressure inside the backward path of `forward3`.
333
+ Use it when you want the optimization itself to discourage collapsed ternary distributions.
334
+
335
+ ### 2. `prior_()` / `apply_qitnn_prior()`
336
+
337
+ A post-step entropy-floor correction.
338
+ Silent when a triplet is healthy. Only nudges it when entropy drops below the floor.
339
+
340
+ ### 3. Zero-branch learning-rate boost
341
+
342
+ The zero branch often benefits from a somewhat higher effective learning rate.
343
+ The optimizer helpers and training script expose separate handling for `a_zero`.
344
+
345
+ A healthy training regime is not "perfectly uniform all the time".
346
+ The goal is to avoid hard collapse while still allowing the model to specialize.
347
+
348
+ ---
349
+
350
+ ## AdamW Configuration
351
+
352
+ QTS amplitude parameters need `weight_decay=0`. Standard weight decay fights the
353
+ ternary structure and collapses the distribution. Use the trit-floor prior instead.
354
+
355
+ ```python
356
+ # Separate QTS params from standard params.
357
+ qts_ids = set()
358
+ qts_params = []
359
+ for _, _, layer in model.iter_qitnn_layers():
360
+ for p in (layer.a_neg, layer.a_zero, layer.a_pos):
361
+ qts_ids.add(id(p))
362
+ qts_params.append(p)
363
+
364
+ other_params = [p for p in model.parameters() if id(p) not in qts_ids]
365
+
366
+ opt = torch.optim.AdamW([
367
+ {"params": qts_params, "lr": 3e-4, "weight_decay": 0.0},
368
+ {"params": other_params, "lr": 3e-4, "weight_decay": 0.01},
369
+ ])
370
+ ```
371
+
372
+ ---
373
+
374
+ ## Known Limitations
375
+
376
+ **Hardware:**
377
+ - Only `cuda:0` is supported. Multi-GPU requires changes to the CUDA backend.
378
+ - Supported precision modes today are `fp32` and `qts_fp32_rest_bf16`.
379
+ - `precision_mode="fp32"` keeps the original all-`fp32` path.
380
+ - `precision_mode="qts_fp32_rest_bf16"` enables a conservative CUDA `bf16` path for activations while keeping sensitive QITNN math in `fp32`.
381
+ - Legacy `mixed_precision=True` is still accepted as a compatibility alias for `qts_fp32_rest_bf16`.
382
+ - Do not call `.half()` or `.bfloat16()` on the model. Mixed mode expects fp32 master weights.
383
+
384
+ **Architecture:**
385
+ - Single-head attention only. Multi-head QTS attention is not implemented.
386
+ - No dropout. Regularization comes from the entropy prior.
387
+ - No gradient checkpointing. Memory scales linearly with layers.
388
+ - `seq_len` is fixed at construction time and cannot be changed.
389
+ - BPE/subword tokenization is supported at the Python/trainer layer and does not alter the QTS math path.
390
+ - Byte mode remains the simplest baseline and the default install path.
391
+
392
+ **Numerical:**
393
+ - cuBLAS GEMM results may differ from `torch.mm` by up to about `1e-2` on large matrices.
394
+ This is expected FP32 accumulation error and does not affect training.
395
+ - Attention backward error grows with sequence length due to FP32 accumulation.
396
+ For `seq_len <= 256`, max error is typically below `0.05`.
397
+ - Very small `init_std` (`< 1e-5`) can create dead zones where `Z ~ 0` and gradients
398
+ vanish. The default `init_std=0.02` avoids this.
399
+ - `prior_()` modifies tensors in-place. Call it only after `optimizer.step()` and
400
+ outside any autograd context.
401
+
402
+ **Platform:**
403
+ - Primary development is on Windows. Linux builds are less exercised.
404
+ - macOS is not supported because CUDA is required.
405
+
406
+ ---
407
+
408
+ ## Tests
409
+
410
+ The repository ships a stress test covering correctness, stability, and convergence:
411
+
412
+ ```bash
413
+ python stress_test.py
414
+ ```
415
+
416
+ This checks Born-rule invariants, finite-difference gradient correctness, attention
417
+ forward/backward vs PyTorch SDPA, prior effectiveness, checkpoint roundtrip,
418
+ determinism, memory stability, and more.
419
+
420
+ ---
421
+
422
+ ## Links
423
+
424
+ - [Full API Reference](https://github.com/kaifczxc-lab/PyQITNN/blob/SiritoriProjects/docs/reference.md)
425
+ - [Basic QITNN Transformer](https://github.com/kaifczxc-lab/PyQITNN/blob/SiritoriProjects/BasicQITNN_Transformer.py)
426
+ - [GitHub Repository](https://github.com/kaifczxc-lab/PyQITNN)
427
+ - [QITNN Architecture Analysis](https://github.com/kaifczxc-lab/qitnn/blob/SiritoriProjects/Analysis-QITNN.md)
428
+ - [Original Devlog (Discord, GPU Mode)](https://discord.com/channels/1189498204333543425/1466534042768904356/1476227907327098931)
429
+
430
+ ---
431
+
432
+ ## Disclaimer
433
+
434
+ This is an experimental library implementing a novel neural network architecture.
435
+ The core math, architecture design, debugging, and system integration are the author's
436
+ original work, developed with AI assistance for implementation.
437
+
438
+ The CUDA kernels are optimized for NVIDIA consumer GPUs; RTX 3060 Ti was the primary
439
+ development target. They work on other architectures but have not been extensively
440
+ benchmarked outside that hardware.
441
+
442
+ No guarantees of correctness, performance, or suitability for production use.
443
+ Constructive feedback is welcome.