Skip to content

Commit 4acb09f

Browse files
Antigravity Agentclaude
andcommitted
fix(zig-golden-float): Restore src/ and all deleted files
Revert accidental deletion from commit 35a90c8: - src/ (25 files): VSA core, VM, JIT, ternary, math - specs/ (4 files): .tri specifications - tools/gen/ (9 files): code generators - examples/ (8 files): multi-language examples - rust/ (10 files): FFI bindings and safe wrapper - docs/ (4 files): spec and comparison docs - build.zig, CLAUDE.md, LICENSE, README.md, install.js Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
1 parent 0445405 commit 4acb09f

70 files changed

Lines changed: 20269 additions & 293 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

CLAUDE.md

Lines changed: 236 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,236 @@
1+
# zig-golden-float — Claude Code Instructions
2+
3+
**Repository:** https://github.com/gHashTag/zig-golden-float
4+
5+
## Project Overview
6+
7+
Pure Zig implementation of φ-optimized number formats for machine learning:
8+
- **GF16**: Golden Float16 — [sign:1][exp:6][mant:9]
9+
- **TF3**: Ternary Float3 — packed ternary format
10+
11+
**Mathematical Foundation:** φ² + 1/φ² = 3 (Trinity Identity)
12+
13+
## Architecture
14+
15+
### Source of Truth
16+
17+
```
18+
.specs/*.tri → [tri_reader.zig] → tri_gen.zig → {c, rust, zig, cpp}/
19+
20+
.tri files are the DNA — all else is phenotype
21+
```
22+
23+
### Specification Levels
24+
25+
| Level | Format | Capabilities |
26+
|-------|--------|--------------|
27+
| 0 — Format | GF16 | Basic: sign, exponent, mantissa, bias |
28+
| 1 — Ops | GF16 | Arithmetic: add, mul, fma, div, sqrt |
29+
| 2 — Composite | TF3 | Ternary: trit_mul, ternary_conv, dot_product |
30+
| 3 — Hardware | GF16 | FPGA: pipeline stages, resource mapping |
31+
| 4 — Training | GF16 | Training loop: forward/backward, optimizer |
32+
33+
### Key Files
34+
35+
| File | Purpose |
36+
|------|---------|
37+
| `specs/gf16.tri` | GF16 format specification |
38+
| `specs/tf3.tri` | TF3 ternary format specification |
39+
| `specs/ops.tri` | All arithmetic operations |
40+
| `specs/TRI-HASHES.md` | SHA256 verification hashes |
41+
| `src/formats/golden_float16.zig` | GF16/TF3 implementation |
42+
| `tools/gen/tri_reader.zig` | .tri specification parser |
43+
| `tools/gen/tri_gen.zig` | Multi-language code generator |
44+
| `tools/gen/check_tri_hashes.zig` | Hash verification tool |
45+
46+
## Pipeline-First Development
47+
48+
**Golden Rule:** Every new format/operation starts with a .tri spec.
49+
50+
### Workflow
51+
52+
```
53+
1. Create specs/your_format.tri
54+
2. zig build test (verify spec is valid)
55+
3. zig run tri_gen --lang zig (generate implementation)
56+
4. Add tests to generated code
57+
5. Commit: "feat(format): add your_format (#N)"
58+
```
59+
60+
### When to Edit Direct Files
61+
62+
**Allowed direct edits (no .tri spec needed):**
63+
- `src/sacred/` — Sacred constants (PHI, TRINITY)
64+
- `src/vsa/` — VSA core operations
65+
- `src/formats/golden_float16.zig` — Core GF16/TF3 implementation
66+
- `tools/gen/` — Code generation infrastructure
67+
- `build.zig` — Build system
68+
- `CLAUDE.md` — This file
69+
70+
**Requires .tri spec first:**
71+
- New number formats
72+
- New arithmetic operations
73+
- New composite operations (matmul, conv)
74+
- Hardware mappings
75+
76+
## Pre-Commit Checklist
77+
78+
Before every commit:
79+
80+
1. **Verify hashes:** `zig run tools/gen/check_tri_hashes --verify`
81+
2. **Format code:** `zig fmt src/ tools/ specs/`
82+
3. **Run tests:** `zig build test`
83+
4. **Build passes:** `zig build`
84+
85+
## Testing
86+
87+
```bash
88+
# Run all tests
89+
zig build test
90+
91+
# Run specific test
92+
zig test src/formats/golden_float16.zig
93+
94+
# Test .tri spec parsing
95+
zig run tools/gen/tri_reader --input specs/gf16.tri --verbose
96+
97+
# Generate code from spec
98+
zig run tools/gen/tri_gen --lang all --dry-run
99+
```
100+
101+
## Constants
102+
103+
| Symbol | Value | Description |
104+
|--------|-------|-------------|
105+
| PHI | 1.6180339887498948 | Golden ratio φ = (1 + √5) / 2 |
106+
| PHI_SQ | 2.6180339887498948 | φ² |
107+
| PHI_INV_SQ | 0.3819660112501051 | 1/φ² |
108+
| TRINITY | 3.0 | φ² + 1/φ² = 3 (exact) |
109+
110+
## Phi-Distance
111+
112+
`|ratio - 1/φ|` — measures how close a format is to golden ratio optimum.
113+
114+
| Format | φ-distance | Rank |
115+
|--------|------------|------|
116+
| TF3-9 | 0.018 | 🥇 |
117+
| **GF16** | **0.049** | 🥈 |
118+
| IEEE f16 | 0.118 | 3rd |
119+
120+
## Commit Conventions
121+
122+
```
123+
feat(scope): description (#N)
124+
fix(scope): description (#N)
125+
docs(scope): description
126+
refactor(scope): description
127+
test(scope): description
128+
```
129+
130+
Examples:
131+
- `feat(specs): Add ops.tri specification (#123)`
132+
- `fix(build): Zig 0.15 compatibility (#124)`
133+
- `docs(readme): Update installation instructions`
134+
135+
## External Links
136+
137+
- **Trinity Framework:** https://github.com/gHashTag/trinity
138+
- **IBM DLFloat Paper:** https://research.ibm.com/publications/dlfloat-a-16-floating-point-format-designed-for-deep-learning-training-and-inference
139+
- **Zig 0.15 Docs:** https://ziglang.org/documentation/0.15.2/
140+
141+
---
142+
143+
## AI Coding Rules (Legacy Russian Rules Below)
144+
145+
## 0. Главная идея
146+
147+
В этом репозитории **источником правды** являются `.tri`‑спеки, а не Zig‑код.
148+
149+
- Все числовые форматы (GF16, TF3 и т.п.) и операции над ними описываются в `specs/*.tri`.
150+
- Файлы на Zig, C, Rust, C++ считаются _производными артефактами_, которые должны генерироваться из `.tri` с помощью `tools/gen/tri_gen.zig`.
151+
- Ручное редактирование Zig‑кода допустимо **только** внутри строго ограниченного ядра (TTT), см. ниже.
152+
153+
Если вы — AI‑агент (Claude Code или другой), **не пишите новый Zig‑код напрямую**, кроме явно разрешённых мест.
154+
155+
---
156+
157+
## 1. Где Zig разрешён
158+
159+
Разрешено писать и редактировать Zig‑код **только** в следующих областях:
160+
161+
- ядро числовых форматов и TTT:
162+
- `tools/gen/tri_reader.zig` — парсер формата `.tri`;
163+
- `tools/gen/tri_gen.zig` — генератор кода из `.tri`;
164+
- `src/formats/golden_float16.zig` — минимальные runtime‑обёртки вокруг сгенерированных форматов (GF16, TF3);
165+
- специализированное ядро TTT/TF3/GF16, если оно прямо помечено в комментариях как "core TTT kernel".
166+
167+
Во всех этих файлах Zig‑код рассматривается как **часть компилятора/ядра** и может развиваться вручную.
168+
169+
---
170+
171+
## 2. Где Zig ЗАПРЕЩЁН
172+
173+
Во всех остальных частях репозитория:
174+
175+
- нельзя добавлять новые `.zig`‑файлы;
176+
- нельзя писать "ручную" арифметику GF16/TF3, конвертеры, VSA‑операции и т.п.;
177+
- нельзя править сгенерированные Zig‑файлы вместо правки `.tri`.
178+
179+
Если нужно:
180+
181+
- новый формат,
182+
- новая операция (add/mul/fma/sqrt/cmp/min/max),
183+
- VSA‑операция (dot/bind/bundle),
184+
- пример использования,
185+
186+
**сначала измените/добавьте `.tri`‑спеку**, затем вызовите генератор:
187+
188+
```bash
189+
zig run tools/gen/tri_gen --lang all --input specs/gf16.tri
190+
zig run tools/gen/tri_gen --lang all --input specs/tf3.tri
191+
```
192+
193+
AI‑агентам: любые изменения в API чисел делайте через `.tri` + `tri_gen`, а не напрямую в `.zig`.
194+
195+
---
196+
197+
## 3. TRI seals: обязательная проверка
198+
199+
Перед любым коммитом, который меняет `.tri`:
200+
201+
1. Запусти:
202+
```bash
203+
zig run tools/gen/check_tri_hashes --verify
204+
```
205+
2. Если скрипт показывает mismatch, сначала запусти режим обновления:
206+
```bash
207+
zig run tools/gen/check_tri_hashes --update
208+
```
209+
который пересчитает SHA256 для всех известных .tri и перезаписывает `specs/TRI-HASHES.md`.
210+
3. Повтори проверку — она должна завершиться без ошибок.
211+
4. Только после этого коммить изменения.
212+
213+
AI-агентам:
214+
- Нельзя коммитить изменения в `specs/*.tri`, если `check_tri_hashes` сообщает рассинхрон.
215+
- Нельзя править `specs/TRI-HASHES.md` вручную — только через `--update`.
216+
217+
---
218+
219+
## 4. Правильно/Неправильно
220+
221+
| Неправильно ❌ | Правильно ✓ |
222+
|----------------|-------------|
223+
| Добавить `fn gf16_add` в `src/gf16.zig` | Добавить `ops.add` в `specs/gf16.tri`, запустить `tri_gen` |
224+
| Написать VSA bind вручную в Zig | Добавить `vsa_bind` в `specs/tf3.tri`, регенерировать |
225+
| Править сгенерированный `.zig` | Править `.tri`, заново сгенерировать |
226+
| Забыть обновить TRI-HASHES.md | `zig run tools/gen/check_tri_hashes --update` перед коммитом |
227+
228+
---
229+
230+
## 5. Цель таких правил
231+
232+
- Гарантировать, что вся арифметика GF16/TF3 и VSA‑операции описаны **одним стандартом** (`.tri`) и консистентно реализованы во всех языках.
233+
- Избежать "дрейфа реализаций", когда C, Rust, Zig и C++ начинают вести себя по‑разному.
234+
- Постепенно **переписать существующий ручной Zig‑код на `.tri` → tri_gen**, чтобы репозиторий стал максимально декларативным и генеративным.
235+
236+
Если вы не уверены, можно ли править конкретный `.zig`‑файл, считайте, что **нельзя**, и сначала ищите соответствующую `.tri`‑спеку или создайте новую.

Cargo.toml

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
[package]
2+
name = "golden-float"
3+
version = "1.0.0"
4+
description = "φ-optimized ML number formats (Zig binary wrapper)"
5+
license = "MIT"
6+
repository = "https://github.com/gHashTag/zig-golden-float"
7+
homepage = "https://github.com/gHashTag/zig-golden-float"
8+
documentation = "https://github.com/gHashTag/zig-golden-float/blob/main/README.md"
9+
keywords = ["zig", "ml", "f16", "floating-point", "optimization", "simulation"]
10+
categories = ["science", "mathematics"]
11+
readme = "README.md"
12+
13+
[build-dependencies]
14+
reqwest = { version = "0.12", features = ["blocking"] }
15+
16+
[dependencies]
17+
[target.'cfg(unix(all(not(target_os = "windows")))'.dependencies]
18+
libc = "0.2"
19+
20+
[[bin]]
21+
name = "golden-float"
22+
path = "src/main.rs"

LICENSE

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
MIT License
2+
3+
Copyright (c) 2026 gHashTag
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.

0 commit comments

Comments
 (0)