rustensor 0.1.0

Small Rust-native checkpoint format for model metadata and tensor weights.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
<a id="readme-top"></a>

<div align="center">

[![Rust](https://img.shields.io/badge/Rust-2024-000000?style=for-the-badge&logo=rust&logoColor=white)](https://www.rust-lang.org/)
[![Crate](https://img.shields.io/badge/Library-Crate-8B4513?style=for-the-badge)](#scope-en)
[![Format](https://img.shields.io/badge/Format-.rten-316192?style=for-the-badge)](#rten-file-layout-en)
[![Release](https://img.shields.io/badge/Release-0.1.0-2ea44f?style=for-the-badge)](#status-en)
[![Phase](https://img.shields.io/badge/Phase-06_Crates_IO_Preparation-5f4b8b?style=for-the-badge)](#status-en)
[![License](https://img.shields.io/badge/license-MIT_OR_Apache--2.0-green?style=for-the-badge)](#license-en)

<h1 align="center">rustensor</h1>

<p align="center">
  <img
    src="assets/rust_repo.png"
    alt="Rustensor crate visual banner"
    width="720"
  />
</p>

<p align="center">
  A small Rust-native checkpoint format for storing model metadata and tensor weights in a single verifiable <code>.rten</code> file.
  <br />
  Un formato pequeno, nativo de Rust, para guardar metadatos de modelo y pesos tensoriales dentro de un unico archivo <code>.rten</code> verificable.
</p>

<p align="center">
  Go to:
  <a href="#english"><strong>English</strong></a>
  |
  <a href="#espanol"><strong>Espanol</strong></a>
</p>

</div>

---

<a id="english"></a>

## English

<details>
<summary><strong>English table of contents</strong></summary>

- [Status](#status-en)
- [Scope](#scope-en)
- [What rustensor is](#what-rustensor-is-en)
- [What rustensor does not do](#what-rustensor-does-not-do-en)
- [RTEN file layout](#rten-file-layout-en)
- [Basic usage](#basic-usage-en)
- [Integrity verification](#integrity-verification-en)
- [Current public API](#current-public-api-en)
- [Project documentation](#project-documentation-en)
- [Project structure](#project-structure-en)
- [Development](#development-en)
- [GitHub Actions](#github-actions-en)
- [Current test coverage](#current-test-coverage-en)
- [Limitations](#limitations-en)
- [Future roadmap](#future-roadmap-en)
- [Crates.io release preparation](#crates-io-release-preparation-en)
- [License](#license-en)
- [Contact](#contact-en)

</details>

---

<a id="status-en"></a>

### Status

Release 0.1.0 is currently in Phase 06.

Phase 00 prepared the Rust library crate structure. Phase 01 defined the fixed 48-byte `.rten` header identity. Phase 02 added the in-memory checkpoint data model. Phase 03 added real `.rten` file writing and reading. Phase 04 added SHA-256 payload integrity verification. Phase 05 consolidated public documentation, executable examples, QA evidence and GitHub Actions CI. Phase 06 prepares the crate for crates.io publication through metadata review, package validation, publish dry-run and release tagging.

At this stage, rustensor can build and validate model metadata, F32 tensor weight layers, complete in-memory checkpoints, write `.rten` files and read them back through a defensive loader that verifies the SHA-256 checksum before deserializing the payload.

Phase 06 does not add a new core file-format capability. It turns the Phase 05 public crate into a publishable release candidate by reviewing Cargo metadata, README, CHANGELOG, licenses, package contents, `cargo package`, `cargo publish --dry-run` and the `v0.1.0` release tag.

<p align="right">(<a href="#readme-top">back to top</a>)</p>

---

<a id="scope-en"></a>

### Scope

rustensor is a small Rust-native checkpoint format.

The goal is to store everything needed to describe and recover a model checkpoint in a single `.rten` file:

- model metadata;
- tensor weight data;
- format version;
- payload length;
- integrity information;
- defensive validation during loading.

The first stable objective is intentionally small:

    Store and load a descriptive, versioned and verifiable checkpoint.

Implemented in Phase 00:

- Rust library crate created.
- Cargo metadata configured.
- Base README created.
- CHANGELOG created.
- Dual MIT OR Apache-2.0 license files created.
- Base technical documentation created under docs/.
- Minimal public API added.
- Unit smoke test added.
- Integration smoke test added.
- Local Rust and Git verification performed.

Implemented in Phase 01:

- Fixed 48-byte `.rten` header layout.
- `RTEN` magic bytes.
- Format version encoded as little-endian `u16`.
- Reserved flags encoded as little-endian `u16`.
- Payload length encoded as little-endian `u64`.
- 32-byte checksum field stored in the header.
- `RtenHeader::new()`.
- `RtenHeader::encode()`.
- `RtenHeader::decode()`.
- Defensive validation for invalid magic bytes, unsupported versions, non-zero flags and oversized payloads.
- Header round-trip tests.

Implemented in Phase 02:

- `serde` derive support for checkpoint data structures.
- `ModelMetadata` for model name, architecture, model version, optional fields and deterministic extra metadata.
- `TensorDType::F32`.
- `TensorData::F32(Vec<f32>)`.
- `WeightLayer` with shape and tensor data validation.
- `ModelCheckpoint` with metadata, layers, duplicate-name validation and maximum layer count validation.
- 15 checkpoint model tests.

Implemented in Phase 03:

- `postcard` payload serialization.
- `save_checkpoint(path, checkpoint)`.
- `load_checkpoint(path)`.
- Fixed 48-byte RTEN header reuse for file writing.
- Defensive header decoding through `RtenHeader::decode()`.
- Payload length validation against the real file size.
- Phase 03 originally validated the reserved checksum field before SHA-256 integrity was added.
- Checkpoint validation before writing.
- Checkpoint validation after reading and decoding.
- 10 checkpoint I/O tests.

Implemented in Phase 04:

- SHA-256 checksum calculation over the serialized payload.
- Real checksum writing in `.rten` headers.
- Checksum verification before payload deserialization.
- Manual SHA-256 hex formatting without external `hex` dependency.
- Constant-time style checksum comparison without external dependency.
- Defensive corruption and truncation tests.
- 12 integrity tests.
- Documentation that integrity is not authenticity.

Implemented in Phase 05:

- Public README updated for review.
- Public documentation scope consolidated.
- GitHub Actions CI planned for formatting, check, clippy, tests, docs and examples.
- Executable examples planned for saving and loading checkpoints.
- Local QA now includes `cargo doc --no-deps`.
- Generated `.rten` files are kept out of version control.

Phase 06 release preparation:

- crates.io package metadata review.
- MSRV declaration with `rust-version = "1.85"`.
- README and CHANGELOG alignment for release `0.1.0`.
- License files verification.
- `.gitignore` verification for generated `.rten` files.
- Package content review with `cargo package --list`.
- Package validation with `cargo package`.
- Publication validation with `cargo publish --dry-run`.
- Release tag preparation with `v0.1.0`.
- Real crates.io publication only after explicit manual confirmation.

<p align="right">(<a href="#readme-top">back to top</a>)</p>

---

<a id="what-rustensor-is-en"></a>

### What rustensor is

rustensor is:

- a Rust library crate;
- a small binary checkpoint container;
- a simple `.rten` file format;
- a format with a fixed 48-byte header;
- a checkpoint serializer and deserializer;
- a validation layer for metadata and tensor shapes;
- a defensive reader for rejecting corrupt or inconsistent files;
- an auditable portfolio-grade Rust project.

<p align="right">(<a href="#readme-top">back to top</a>)</p>

---

<a id="what-rustensor-does-not-do-en"></a>

### What rustensor does not do

rustensor is not a machine learning framework.

In version 0.1.0, it does not:

- train models;
- run inference;
- replace ONNX;
- replace GGUF;
- replace SafeTensors;
- implement real tokenizers;
- implement autograd;
- use GPU;
- provide HTTP endpoints;
- use a database;
- provide cryptographic authenticity;
- provide HMAC or digital signatures;
- provide automatic PyTorch compatibility.

Integrity verification is implemented with SHA-256 over the payload, but authenticity remains out of scope for v0.1.0.

<p align="right">(<a href="#readme-top">back to top</a>)</p>

---

<a id="rten-file-layout-en"></a>

### RTEN file layout

A `.rten` file has two main parts:

```text
[0..48]   fixed RTEN header
[48..]    serialized checkpoint payload
```

The fixed 48-byte header uses this layout:

```text
[0..4]    magic bytes: RTEN
[4..6]    format version: u16 little-endian
[6..8]    flags: u16 little-endian
[8..16]   payload length: u64 little-endian
[16..48]  SHA-256 checksum of payload
```

The payload contains a serialized `ModelCheckpoint`.

The checksum is calculated only over the payload, not over the header.

<p align="right">(<a href="#readme-top">back to top</a>)</p>

---

<a id="basic-usage-en"></a>

### Basic usage

```rust
use rustensor::{load_checkpoint, save_checkpoint, ModelCheckpoint, ModelMetadata, WeightLayer};

fn main() -> rustensor::Result<()> {
    let metadata = ModelMetadata::new(
        "demo-model".to_string(),
        "linear".to_string(),
        "0.1.0".to_string(),
    )?;

    let layer = WeightLayer::f32(
        "dense.weight".to_string(),
        vec![2, 2],
        vec![0.1, 0.2, 0.3, 0.4],
    )?;

    let mut checkpoint = ModelCheckpoint::new(metadata);
    checkpoint.add_layer(layer)?;

    save_checkpoint("demo_model.rten", &checkpoint)?;

    let loaded = load_checkpoint("demo_model.rten")?;

    assert_eq!(loaded.metadata.model_name, "demo-model");
    assert_eq!(loaded.layers.len(), 1);

    Ok(())
}
```

<p align="right">(<a href="#readme-top">back to top</a>)</p>

---

<a id="integrity-verification-en"></a>

### Integrity verification

rustensor stores a SHA-256 checksum of the serialized payload in the `.rten` header.

The checksum is calculated only over the payload, not over the header. This avoids circular hashing and keeps the fixed header parseable before reading the full payload.

When saving a checkpoint:

1. The checkpoint is validated.
2. The checkpoint payload is serialized.
3. SHA-256 is calculated over the payload.
4. The RTEN header is written with the payload length and checksum.
5. The header and payload are written to disk.

When loading a checkpoint:

1. The file is read from disk.
2. The fixed RTEN header is decoded.
3. Magic bytes, version, flags and payload length are verified.
4. The payload is extracted.
5. The SHA-256 checksum is recalculated.
6. The checksum from the header is compared with the recalculated checksum.
7. The payload is decoded.
8. The decoded checkpoint is validated.

SHA-256 integrity verification detects accidental corruption or unintended modification.
It is not a digital signature and does not prove file authenticity.

For authenticity, a future design would require HMAC, digital signatures or another trust mechanism outside the current v0.1.0 scope.

<p align="right">(<a href="#readme-top">back to top</a>)</p>

---

<a id="current-public-api-en"></a>

### Current public API

The public API exposes the in-memory checkpoint model, the RTEN header identity and the save/load API.

```rust
use rustensor::{load_checkpoint, save_checkpoint};

save_checkpoint("model.rten", &checkpoint)?;

let loaded = load_checkpoint("model.rten")?;
```

Current API:

| Item | Purpose |
|---|---|
| `CRATE_NAME` | Public crate name constant. |
| `crate_name()` | Minimal public function used by smoke tests. |
| `RtenHeader` | Fixed `.rten` header model from Phase 01. |
| `ModelMetadata` | Descriptive model metadata. |
| `WeightLayer` | Named tensor weight layer. |
| `TensorDType` | Supported tensor dtype enum. |
| `TensorData` | Supported tensor data enum. |
| `ModelCheckpoint` | Root in-memory checkpoint structure. |
| `save_checkpoint()` | Writes a validated checkpoint to a `.rten` file. |
| `load_checkpoint()` | Reads a `.rten` file, validates its header, verifies checksum and decodes the checkpoint. |

<p align="right">(<a href="#readme-top">back to top</a>)</p>

---

<a id="project-documentation-en"></a>

### Project documentation

Additional technical documentation is available in the docs folder.

| Document | Description |
|---|---|
| `docs/ARCHITECTURE.md` | Describes the architecture and scope boundaries. |
| `docs/CRATE_FLOW.md` | Explains the save/load flow of the crate. |
| `docs/REVIEWER_GUIDE.md` | Short guide for reviewers, recruiters or technical readers. |

<p align="right">(<a href="#readme-top">back to top</a>)</p>

---

<a id="project-structure-en"></a>

### Project structure

Current Phase 06 structure:

```text
rustensor/
|-- .github/
|   +-- workflows/
|       +-- rust.yml
|-- Cargo.toml
|-- README.md
|-- CHANGELOG.md
|-- LICENSE-MIT
|-- LICENSE-APACHE
|-- .gitignore
|-- assets/
|   |-- rust_repo.png
|-- docs/
|   |-- ARCHITECTURE.md
|   |-- CRATE_FLOW.md
|   +-- REVIEWER_GUIDE.md
|-- examples/
|   |-- save_checkpoint.rs
|   +-- load_checkpoint.rs
|-- src/
|   |-- checkpoint.rs
|   |-- error.rs
|   |-- format.rs
|   |-- integrity.rs
|   |-- lib.rs
|   |-- metadata.rs
|   |-- reader.rs
|   |-- weights.rs
|   +-- writer.rs
+-- tests/
    |-- checkpoint_io_test.rs
    |-- checkpoint_model_test.rs
    |-- format_header_test.rs
    |-- integrity_test.rs
    +-- smoke_test.rs
```

<p align="right">(<a href="#readme-top">back to top</a>)</p>

---

<a id="development-en"></a>

### Development

Recommended local QA:

```powershell
cargo fmt
cargo fmt --check
cargo check --all-targets
cargo clippy --all-targets -- -D warnings
cargo test
cargo doc --no-deps
cargo run --example save_checkpoint
cargo run --example load_checkpoint
git status --short
```

The project is developed phase by phase.
Each phase must pass local QA before being closed.

<p align="right">(<a href="#readme-top">back to top</a>)</p>

---

<a id="github-actions-en"></a>

### GitHub Actions

Phase 05 adds a Rust CI workflow under:

```text
.github/workflows/rust.yml
```

The workflow validates:

- formatting;
- compilation;
- Clippy;
- tests;
- documentation;
- executable examples.

<p align="right">(<a href="#readme-top">back to top</a>)</p>

---

<a id="current-test-coverage-en"></a>

### Current test coverage

Current expected result after Phase 06 QA:

    54 tests passing

Current test groups:

| Phase | Tests | Purpose |
|---|---:|---|
| Phase 00 | 2 | Crate smoke tests. |
| Phase 01 | 15 | RTEN header identity, encode/decode and defensive validation. |
| Phase 02 | 15 | Metadata, F32 layers, shapes, tensor data, duplicates and layer limit. |
| Phase 03 | 10 | RTEN file round-trip and defensive reader checks. |
| Phase 04 | 12 | SHA-256 integrity helpers, checksum verification, corruption and truncation tests. |
| Phase 05 | 0 | Public documentation, examples, QA and CI. |
| Phase 06 | 0 | crates.io preparation, package validation and publish dry-run. |

Planned total for the project:

| Phase | Planned tests |
|---|---:|
| Phase 00 | 2 |
| Phase 01 | 15 |
| Phase 02 | 15 |
| Phase 03 | 10 |
| Phase 04 | 12 |
| Phase 05 | 0 new |
| Phase 06 | 0 new |
| Total | 54 |

<p align="right">(<a href="#readme-top">back to top</a>)</p>

---

<a id="limitations-en"></a>

### Limitations

rustensor does not train models.
rustensor does not run inference.
rustensor does not implement autograd.
rustensor does not implement ONNX.
rustensor does not replace GGUF or SafeTensors.
rustensor does not implement tokenizers.
rustensor does not provide digital signatures.
rustensor SHA-256 verification detects accidental corruption but does not prove authenticity.

<p align="right">(<a href="#readme-top">back to top</a>)</p>

---

<a id="future-roadmap-en"></a>

### Future roadmap

| Phase | Goal |
|---|---|
| Phase 00 | Prepare crate and initial structure. |
| Phase 01 | Define `.rten` binary identity and fixed header. |
| Phase 02 | Implement checkpoint data model. |
| Phase 03 | Implement `.rten` save and load. |
| Phase 04 | Implement SHA-256 integrity and defensive loading. |
| Phase 05 | Consolidate public documentation, examples, QA and CI. |
| Phase 06 | Prepare package and manual crates.io release. |

<p align="right">(<a href="#readme-top">back to top</a>)</p>

---

<a id="crates-io-release-preparation-en"></a>

### Crates.io release preparation

Phase 06 prepares rustensor as a crates.io-ready release candidate.

Before any real publication, the release must confirm:

- README complete and aligned with release `0.1.0`.
- CHANGELOG updated with public SemVer release wording.
- Licenses present: `LICENSE-MIT` and `LICENSE-APACHE`.
- Cargo metadata reviewed: version, edition, MSRV, license, description, repository, keywords and categories.
- CI green.
- Local QA green.
- `cargo package --list` reviewed.
- `cargo package` validated.
- `cargo publish --dry-run` validated.
- Git status clean.
- Release tag `v0.1.0` created and pushed when appropriate.
- Real crates.io publication reviewed manually.

Real publication with `cargo publish` is intentionally manual and must only happen after explicit confirmation.

<p align="right">(<a href="#readme-top">back to top</a>)</p>

---

<a id="license-en"></a>

### License

This project is licensed under either of the following licenses, at your option:

- MIT License
- Apache License 2.0

<p align="right">(<a href="#readme-top">back to top</a>)</p>

---

<a id="contact-en"></a>

### Contact

Technical Lead:

    Ing. Elmer Nelson Saucedo Lopez
    AI Software Developer | Python Backend | RAG, NLP, PostgreSQL & Automation | Rust Backend Projects
    Project type: Professional technical portfolio Rust crate

<p align="right">(<a href="#readme-top">back to top</a>)</p>

---

<a id="espanol"></a>

## Espanol

<details>
<summary><strong>Tabla de contenidos en Espanol</strong></summary>

- [Estado](#estado-es)
- [Alcance](#alcance-es)
- [Que es rustensor](#que-es-rustensor-es)
- [Lo que rustensor no hace](#lo-que-rustensor-no-hace-es)
- [Layout del archivo RTEN](#layout-del-archivo-rten-es)
- [Uso basico](#uso-basico-es)
- [Verificacion de integridad](#verificacion-de-integridad-es)
- [API publica actual](#api-publica-actual-es)
- [Documentacion del proyecto](#documentacion-del-proyecto-es)
- [Estructura del proyecto](#estructura-del-proyecto-es)
- [Desarrollo](#desarrollo-es)
- [GitHub Actions](#github-actions-es)
- [Cobertura actual de pruebas](#cobertura-actual-de-pruebas-es)
- [Limitaciones](#limitaciones-es)
- [Ruta futura](#ruta-futura-es)
- [Preparacion de release crates.io](#preparacion-de-release-crates-io-es)
- [Licencia](#licencia-es)
- [Contacto](#contacto-es)

</details>

---

<a id="estado-es"></a>

### Estado

Release 0.1.0 se encuentra actualmente en Fase 06.

La Fase 00 preparo la estructura del crate Rust. La Fase 01 definio la identidad del header fijo `.rten` de 48 bytes. La Fase 02 agrego el modelo de datos del checkpoint en memoria. La Fase 03 agrego escritura y lectura real de archivos `.rten`. La Fase 04 agrego verificacion de integridad SHA-256 sobre el payload. La Fase 05 consolido documentacion publica, ejemplos ejecutables, evidencia de QA y GitHub Actions CI. La Fase 06 prepara el crate para publicacion en crates.io mediante revision de metadata, validacion de paquete, publish dry-run y tag de release.

En este punto, rustensor puede construir y validar metadata de modelo, capas de pesos tensoriales F32, checkpoints completos en memoria, escribir archivos `.rten` y leerlos nuevamente mediante un loader defensivo que verifica el checksum SHA-256 antes de deserializar el payload.

La Fase 06 no agrega una nueva capacidad central al formato de archivo. Convierte el crate publico de Fase 05 en un candidato de release publicable mediante revision de Cargo metadata, README, CHANGELOG, licencias, contenido del paquete, `cargo package`, `cargo publish --dry-run` y tag `v0.1.0`.

<p align="right">(<a href="#readme-top">volver arriba</a>)</p>

---

<a id="alcance-es"></a>

### Alcance

rustensor es un formato pequeno, nativo de Rust, para checkpoints.

El objetivo es guardar todo lo necesario para describir y recuperar un checkpoint de modelo dentro de un unico archivo `.rten`:

- metadata de modelo;
- datos de pesos tensoriales;
- version de formato;
- longitud del payload;
- informacion de integridad;
- validacion defensiva durante la carga.

El primer objetivo estable es intencionalmente pequeno:

    Guardar y cargar un checkpoint descriptivo, versionado y verificable.

Implementado en Fase 00:

- Crate Rust de libreria creado.
- Metadata de Cargo configurada.
- README base creado.
- CHANGELOG creado.
- Licencias duales MIT OR Apache-2.0 creadas.
- Documentacion tecnica base creada en docs/.
- API publica minima agregada.
- Test unitario smoke agregado.
- Test de integracion smoke agregado.
- Verificacion local de Rust y Git realizada.

Implementado en Fase 01:

- Header `.rten` fijo de 48 bytes.
- Magic bytes `RTEN`.
- Version de formato codificada como `u16` little-endian.
- Flags reservados codificados como `u16` little-endian.
- Longitud del payload codificada como `u64` little-endian.
- Campo checksum de 32 bytes almacenado en el header.
- `RtenHeader::new()`.
- `RtenHeader::encode()`.
- `RtenHeader::decode()`.
- Validacion defensiva para magic bytes invalidos, versiones no soportadas, flags distintos de cero y payloads demasiado grandes.
- Tests de round-trip del header.

Implementado en Fase 02:

- Soporte `serde` derive para estructuras de checkpoint.
- `ModelMetadata` para nombre del modelo, arquitectura, version, campos opcionales y metadata extra deterministica.
- `TensorDType::F32`.
- `TensorData::F32(Vec<f32>)`.
- `WeightLayer` con validacion de shape y datos tensoriales.
- `ModelCheckpoint` con metadata, capas, validacion de nombres duplicados y limite maximo de capas.
- 15 tests del modelo de checkpoint.

Implementado en Fase 03:

- Serializacion de payload con `postcard`.
- `save_checkpoint(path, checkpoint)`.
- `load_checkpoint(path)`.
- Reutilizacion del header RTEN fijo de 48 bytes para escritura.
- Decodificacion defensiva del header mediante `RtenHeader::decode()`.
- Validacion de payload length contra el tamano real del archivo.
- En Fase 03 se validaba el campo checksum reservado antes de agregar integridad SHA-256.
- Validacion del checkpoint antes de escribir.
- Validacion del checkpoint despues de leer y decodificar.
- 10 tests de I/O de checkpoint.

Implementado en Fase 04:

- Calculo de checksum SHA-256 sobre el payload serializado.
- Escritura de checksum real en headers `.rten`.
- Verificacion del checksum antes de deserializar el payload.
- Formato hexadecimal SHA-256 manual sin dependencia externa `hex`.
- Comparacion de checksum estilo constante sin dependencia externa.
- Pruebas defensivas de corrupcion y truncamiento.
- 12 tests de integridad.
- Documentacion de que integridad no es autenticidad.

Implementado en Fase 05:

- README publico actualizado para revision.
- Alcance de documentacion publica consolidado.
- GitHub Actions CI planificado para formato, check, clippy, tests, docs y ejemplos.
- Ejemplos ejecutables planificados para guardar y cargar checkpoints.
- QA local ahora incluye `cargo doc --no-deps`.
- Archivos `.rten` generados quedan fuera de control de versiones.

Preparacion de release en Fase 06:

- Revision de metadata del paquete para crates.io.
- Declaracion de MSRV con `rust-version = "1.85"`.
- Alineacion de README y CHANGELOG para release `0.1.0`.
- Verificacion de archivos de licencia.
- Verificacion de `.gitignore` para archivos `.rten` generados.
- Revision de contenido del paquete con `cargo package --list`.
- Validacion del paquete con `cargo package`.
- Validacion de publicacion con `cargo publish --dry-run`.
- Preparacion del tag de release `v0.1.0`.
- Publicacion real en crates.io solamente con confirmacion manual explicita.

<p align="right">(<a href="#readme-top">volver arriba</a>)</p>

---

<a id="que-es-rustensor-es"></a>

### Que es rustensor

rustensor es:

- un crate Rust de libreria;
- un contenedor binario pequeno para checkpoints;
- un formato simple de archivo `.rten`;
- un formato con header fijo de 48 bytes;
- un serializador y deserializador de checkpoints;
- una capa de validacion para metadata y shapes tensoriales;
- un lector defensivo para rechazar archivos corruptos o inconsistentes;
- un proyecto Rust auditable para portafolio tecnico.

<p align="right">(<a href="#readme-top">volver arriba</a>)</p>

---

<a id="lo-que-rustensor-no-hace-es"></a>

### Lo que rustensor no hace

rustensor no es un framework de machine learning.

En version 0.1.0, no hace:

- entrenamiento de modelos;
- inferencia;
- reemplazo de ONNX;
- reemplazo de GGUF;
- reemplazo de SafeTensors;
- tokenizers reales;
- autograd;
- GPU;
- endpoints HTTP;
- base de datos;
- autenticidad criptografica;
- HMAC o firmas digitales;
- compatibilidad automatica con PyTorch.

La verificacion de integridad esta implementada con SHA-256 sobre el payload, pero la autenticidad queda fuera del alcance de v0.1.0.

<p align="right">(<a href="#readme-top">volver arriba</a>)</p>

---

<a id="layout-del-archivo-rten-es"></a>

### Layout del archivo RTEN

Un archivo `.rten` tiene dos partes principales:

```text
[0..48]   header RTEN fijo
[48..]    payload serializado del checkpoint
```

El header fijo de 48 bytes usa este layout:

```text
[0..4]    magic bytes: RTEN
[4..6]    version de formato: u16 little-endian
[6..8]    flags: u16 little-endian
[8..16]   longitud del payload: u64 little-endian
[16..48]  checksum SHA-256 del payload
```

El payload contiene un `ModelCheckpoint` serializado.

El checksum se calcula solamente sobre el payload, no sobre el header.

<p align="right">(<a href="#readme-top">volver arriba</a>)</p>

---

<a id="uso-basico-es"></a>

### Uso basico

```rust
use rustensor::{load_checkpoint, save_checkpoint, ModelCheckpoint, ModelMetadata, WeightLayer};

fn main() -> rustensor::Result<()> {
    let metadata = ModelMetadata::new(
        "demo-model".to_string(),
        "linear".to_string(),
        "0.1.0".to_string(),
    )?;

    let layer = WeightLayer::f32(
        "dense.weight".to_string(),
        vec![2, 2],
        vec![0.1, 0.2, 0.3, 0.4],
    )?;

    let mut checkpoint = ModelCheckpoint::new(metadata);
    checkpoint.add_layer(layer)?;

    save_checkpoint("demo_model.rten", &checkpoint)?;

    let loaded = load_checkpoint("demo_model.rten")?;

    assert_eq!(loaded.metadata.model_name, "demo-model");
    assert_eq!(loaded.layers.len(), 1);

    Ok(())
}
```

<p align="right">(<a href="#readme-top">volver arriba</a>)</p>

---

<a id="verificacion-de-integridad-es"></a>

### Verificacion de integridad

rustensor almacena un checksum SHA-256 del payload serializado dentro del header `.rten`.

El checksum se calcula solamente sobre el payload, no sobre el header. Esto evita hashing circular y permite interpretar el header fijo antes de leer el payload completo.

Al guardar un checkpoint:

1. El checkpoint se valida.
2. El payload del checkpoint se serializa.
3. Se calcula SHA-256 sobre el payload.
4. Se escribe el header RTEN con la longitud del payload y el checksum.
5. Se escriben el header y el payload en disco.

Al cargar un checkpoint:

1. El archivo se lee desde disco.
2. El header RTEN fijo se decodifica.
3. Se verifican magic bytes, version, flags y longitud del payload.
4. Se extrae el payload.
5. Se recalcula el checksum SHA-256.
6. El checksum del header se compara con el checksum recalculado.
7. El payload se decodifica.
8. El checkpoint decodificado se valida.

La verificacion de integridad SHA-256 detecta corrupcion accidental o modificacion no intencional.
No es una firma digital y no prueba la autenticidad del archivo.

Para autenticidad, un diseno futuro requeriria HMAC, firmas digitales u otro mecanismo de confianza fuera del alcance actual de v0.1.0.

<p align="right">(<a href="#readme-top">volver arriba</a>)</p>

---

<a id="api-publica-actual-es"></a>

### API publica actual

La API publica expone el modelo de checkpoint en memoria, la identidad del header RTEN y la API de guardado/carga.

```rust
use rustensor::{load_checkpoint, save_checkpoint};

save_checkpoint("model.rten", &checkpoint)?;

let loaded = load_checkpoint("model.rten")?;
```

API actual:

| Item | Proposito |
|---|---|
| `CRATE_NAME` | Constante publica con el nombre del crate. |
| `crate_name()` | Funcion publica minima usada por smoke tests. |
| `RtenHeader` | Modelo del header fijo `.rten` de Fase 01. |
| `ModelMetadata` | Metadata descriptiva del modelo. |
| `WeightLayer` | Capa nombrada de pesos tensoriales. |
| `TensorDType` | Enum de dtype tensorial soportado. |
| `TensorData` | Enum de datos tensoriales soportados. |
| `ModelCheckpoint` | Estructura raiz del checkpoint en memoria. |
| `save_checkpoint()` | Escribe un checkpoint validado en un archivo `.rten`. |
| `load_checkpoint()` | Lee un archivo `.rten`, valida su header, verifica checksum y decodifica el checkpoint. |

<p align="right">(<a href="#readme-top">volver arriba</a>)</p>

---

<a id="documentacion-del-proyecto-es"></a>

### Documentacion del proyecto

La documentacion tecnica adicional esta disponible en la carpeta docs.

| Documento | Descripcion |
|---|---|
| `docs/ARCHITECTURE.md` | Describe la arquitectura y los limites de alcance. |
| `docs/CRATE_FLOW.md` | Explica el flujo de guardado/carga del crate. |
| `docs/REVIEWER_GUIDE.md` | Guia corta para revisores, reclutadores o lectores tecnicos. |

<p align="right">(<a href="#readme-top">volver arriba</a>)</p>

---

<a id="estructura-del-proyecto-es"></a>

### Estructura del proyecto

Estructura actual de Fase 06:

```text
rustensor/
|-- .github/
|   +-- workflows/
|       +-- rust.yml
|-- Cargo.toml
|-- README.md
|-- CHANGELOG.md
|-- LICENSE-MIT
|-- LICENSE-APACHE
|-- .gitignore
|-- assets/
|   |-- rust_repo.png
|-- docs/
|   |-- ARCHITECTURE.md
|   |-- CRATE_FLOW.md
|   +-- REVIEWER_GUIDE.md
|-- examples/
|   |-- save_checkpoint.rs
|   +-- load_checkpoint.rs
|-- src/
|   |-- checkpoint.rs
|   |-- error.rs
|   |-- format.rs
|   |-- integrity.rs
|   |-- lib.rs
|   |-- metadata.rs
|   |-- reader.rs
|   |-- weights.rs
|   +-- writer.rs
+-- tests/
    |-- checkpoint_io_test.rs
    |-- checkpoint_model_test.rs
    |-- format_header_test.rs
    |-- integrity_test.rs
    +-- smoke_test.rs
```

<p align="right">(<a href="#readme-top">volver arriba</a>)</p>

---

<a id="desarrollo-es"></a>

### Desarrollo

QA local recomendado:

```powershell
cargo fmt
cargo fmt --check
cargo check --all-targets
cargo clippy --all-targets -- -D warnings
cargo test
cargo doc --no-deps
cargo run --example save_checkpoint
cargo run --example load_checkpoint
git status --short
```

El proyecto se desarrolla fase por fase.
Cada fase debe pasar QA local antes de cerrarse.

<p align="right">(<a href="#readme-top">volver arriba</a>)</p>

---

<a id="github-actions-es"></a>

### GitHub Actions

La Fase 05 agrega un workflow Rust CI en:

```text
.github/workflows/rust.yml
```

El workflow valida:

- formato;
- compilacion;
- Clippy;
- tests;
- documentacion;
- ejemplos ejecutables.

<p align="right">(<a href="#readme-top">volver arriba</a>)</p>

---

<a id="cobertura-actual-de-pruebas-es"></a>

### Cobertura actual de pruebas

Resultado esperado actual despues del QA de Fase 06:

    54 tests passing

Grupos actuales de pruebas:

| Fase | Tests | Proposito |
|---|---:|---|
| Fase 00 | 2 | Smoke tests del crate. |
| Fase 01 | 15 | Identidad del header RTEN, encode/decode y validacion defensiva. |
| Fase 02 | 15 | Metadata, capas F32, shapes, datos tensoriales, duplicados y limite de capas. |
| Fase 03 | 10 | Round-trip de archivos RTEN y validaciones defensivas del reader. |
| Fase 04 | 12 | Helpers SHA-256, verificacion de checksum, corrupcion y truncamiento. |
| Fase 05 | 0 | Documentacion publica, ejemplos, QA y CI. |
| Fase 06 | 0 | Preparacion crates.io, validacion de paquete y publish dry-run. |

Total planificado para el proyecto:

| Fase | Tests planificados |
|---|---:|
| Fase 00 | 2 |
| Fase 01 | 15 |
| Fase 02 | 15 |
| Fase 03 | 10 |
| Fase 04 | 12 |
| Fase 05 | 0 nuevos |
| Fase 06 | 0 nuevos |
| Total | 54 |

<p align="right">(<a href="#readme-top">volver arriba</a>)</p>

---

<a id="limitaciones-es"></a>

### Limitaciones

rustensor no entrena modelos.
rustensor no ejecuta inferencia.
rustensor no implementa autograd.
rustensor no implementa ONNX.
rustensor no reemplaza GGUF ni SafeTensors.
rustensor no implementa tokenizers.
rustensor no provee firmas digitales.
La verificacion SHA-256 de rustensor detecta corrupcion accidental, pero no prueba autenticidad.

<p align="right">(<a href="#readme-top">volver arriba</a>)</p>

---

<a id="ruta-futura-es"></a>

### Ruta futura

| Fase | Objetivo |
|---|---|
| Fase 00 | Preparar crate y estructura inicial. |
| Fase 01 | Definir identidad binaria `.rten` y header fijo. |
| Fase 02 | Implementar modelo de datos del checkpoint. |
| Fase 03 | Implementar guardado y carga de `.rten`. |
| Fase 04 | Implementar integridad SHA-256 y carga defensiva. |
| Fase 05 | Consolidar documentacion publica, ejemplos, QA y CI. |
| Fase 06 | Preparar paquete y release manual en crates.io. |

<p align="right">(<a href="#readme-top">volver arriba</a>)</p>

---

<a id="preparacion-de-release-crates-io-es"></a>

### Preparacion de release crates.io

La Fase 06 prepara rustensor como candidato de release listo para crates.io.

Antes de cualquier publicacion real, el release debe confirmar:

- README completo y alineado con release `0.1.0`.
- CHANGELOG actualizado con version publica SemVer.
- Licencias presentes: `LICENSE-MIT` y `LICENSE-APACHE`.
- Metadata de Cargo revisada: version, edition, MSRV, licencia, descripcion, repositorio, keywords y categories.
- CI en verde.
- QA local en verde.
- `cargo package --list` revisado.
- `cargo package` validado.
- `cargo publish --dry-run` validado.
- Estado Git limpio.
- Tag de release `v0.1.0` creado y pusheado cuando corresponda.
- Publicacion real en crates.io revisada manualmente.

La publicacion real con `cargo publish` es intencionalmente manual y solo debe hacerse con confirmacion explicita.

<p align="right">(<a href="#readme-top">volver arriba</a>)</p>

---

<a id="licencia-es"></a>

### Licencia

Este proyecto esta licenciado bajo cualquiera de las siguientes licencias, a eleccion del usuario:

- MIT License
- Apache License 2.0

<p align="right">(<a href="#readme-top">volver arriba</a>)</p>

---

<a id="contacto-es"></a>

### Contacto

Responsable tecnico:

    Ing. Elmer Nelson Saucedo Lopez
    AI Software Developer | Python Backend | RAG, NLP, PostgreSQL & Automation | Rust Backend Projects
    Tipo de proyecto: Crate Rust de portafolio tecnico profesional

<p align="right">(<a href="#readme-top">volver arriba</a>)</p>