<a id="readme-top"></a>
<div align="center">
[](https://www.rust-lang.org/)
[](#scope-en)
[](#rten-file-layout-en)
[](#status-en)
[](#status-en)
[](#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>