Metadata-Version: 2.4
Name: zerocopy-stream
Version: 0.1.0
Summary: Zero-Disk Streaming DataLoader SDK en C++23 / PyTorch para entrenamiento masivo de IA de Leandro Emanuel Timberini
Author-email: Leandro Emanuel Timberini <leaatimberini@gmail.com>
License: AGPL-3.0-or-later
Project-URL: Homepage, https://github.com/leaatimberini/ZeroCopy
Project-URL: Repository, https://github.com/leaatimberini/ZeroCopy.git
Project-URL: Issues, https://github.com/leaatimberini/ZeroCopy/issues
Keywords: pytorch,dataloader,zero-copy,streaming,huggingface,llm,deep-learning,c++23,gpus,amd,rocm
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Science/Research
Classifier: License :: OSI Approved :: GNU Affero General Public License v3 or later (AGPLv3+)
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: torch>=2.0.0
Requires-Dist: datasets>=2.14.0
Requires-Dist: transformers>=4.30.0
Requires-Dist: psutil>=5.9.0
Dynamic: license-file

# ZeroCopy-Stream SDK
### High-Throughput Zero-Disk Streaming DataLoader for Enterprise AI Pre-Training
### *Motor de Ingesta Streaming Zero-Disk de Alto Rendimiento para Pre-Entrenamiento de IA Enterprise*

**Creator & Lead Architect / Creador y Arquitecto Principal**: Leandro Emanuel Timberini  
**Location / Ubicación**: Ituzaingó, Buenos Aires, Argentina  
**License / Licencia**: Dual License (AGPL-3.0 Open-Source & Enterprise Commercial B2B)  
**Language / Lenguajes**: C++23 Bare-Metal Core with Native Python / PyTorch Bindings  

---

## 🌐 Language Switch / Selección de Idioma
- 🇬🇧 [English Documentation](#-english-documentation)
- 🇪🇸 [Documentación en Español](#-documentación-en-español)

---

# 🇬🇧 ENGLISH DOCUMENTATION

## Executive Overview
**ZeroCopy-Stream SDK** is an enterprise-grade high-performance data ingestion engine engineered to eliminate local storage overhead during LLM pre-training (Transformers, PyTorch, DeepSpeed, Megatron-LM, vLLM).

Standard pre-training pipelines require downloading and staging Terabytes/Petabytes of `.parquet` / `.arrow` dataset files onto expensive NVMe SSD RAID server arrays, causing:
1. **Severe Storage Costs**: Hundreds of thousands of dollars spent on cloud NVMe persistent disks (AWS EBS, GCP Persistent Disks).
2. **Hardware Degradation**: Massive continuous SSD write endurance limits ($TBW$) wear out drive life quickly.
3. **PCIe I/O Bottlenecks**: GPUs/TPUs stall waiting for local disk reads.

**ZeroCopy-Stream SDK** streams raw dataset batches directly from network endpoints (Hugging Face, S3, WebRTC, custom HTTP endpoints) into a **Lock-Free RAM Ring-Buffer (DDR5 / HBM)** using zero-copy memory mapping (`VirtualAlloc` / `mmap` / `hipHostMallocMapped`) with **0 Bytes written to local disk**.

---

## 📋 Prerequisites & Installation

### System Requirements
- **OS**: Windows 10/11, Linux (Ubuntu 22.04+), or macOS (Apple Silicon).
- **Python**: Python 3.10 or higher.
- **C++ Compiler**: Clang 17+, GCC 13+, or MSVC 2022 (C++23 support).

### Python Dependencies
```bash
pip install torch datasets huggingface_hub pyarrow psutil
```

---

## 🔑 Hugging Face Authentication & Tokens

* **Public Datasets** (e.g. `FineWeb-Edu`, `OpenWebMath`, `wikitext`): **No token required**.
* **Private / Gated Datasets** (e.g. `meta-llama/Llama-3`, gated code repos): **Authentication Token required**.

### Option A: Via Hugging Face CLI (Recommended)
```bash
huggingface-cli login
```

### Option B: Via Environment Variable
**Windows PowerShell**:
```powershell
$env:HF_TOKEN="hf_YourHuggingFaceAccessTokenHere"
```
**Linux / macOS**:
```bash
export HF_TOKEN="hf_YourHuggingFaceAccessTokenHere"
```

### Option C: Direct Parameter in Python
```python
from zerocopy_stream import ZeroCopyStreamDataLoader

dataloader = ZeroCopyStreamDataLoader(
    dataset_name="meta-llama/Llama-3-Dataset",
    hf_token="hf_YourHuggingFaceAccessTokenHere",
    batch_size="auto"
)
```

---

## ⚙️ Parameter Configuration & Hardware Tuning

Both `buffer_size_gb` and `batch_size` are **fully variable parameters**. You can specify exact numbers or pass `"auto"` to let the SDK detect your hardware and auto-tune parameters.

### 1. `buffer_size_gb` (RAM Ring-Buffer Size)
$$\text{Buffer Size (GB)} \approx \text{Total System RAM} \times 0.30$$

| System RAM Available | Target Environment | Recommended `buffer_size_gb` |
| :--- | :--- | :--- |
| **16 GB RAM** | APU (Ryzen 5 8600G) / Laptop | `2.0` to `4.0` GB |
| **32 GB RAM** | Desktop Workstation | `8.0` to `12.0` GB |
| **64 GB - 128 GB RAM**| High-End AI Workstation | `16.0` to `32.0` GB |
| **256 GB - 1 TB+ RAM**| Cloud Enterprise Cluster (H100 / A100) | `64.0` to `128.0` GB |

### 2. `batch_size` (PyTorch Batch Size per Step)
$$\text{Batch Size} = \frac{\text{Available GPU VRAM}}{\text{Model Memory per Sample} \times \text{Sequence Length}}$$

| GPU VRAM Available | Recommended `batch_size` (Seq Len = 2048) |
| :--- | :--- |
| **8 GB VRAM** (RTX 3060) | `8` to `16` |
| **16 GB VRAM** (RTX 4060 Ti) | `32` to `48` |
| **24 GB VRAM** (RTX 3090 / 4090) | `64` to `128` |
| **80 GB VRAM** (NVIDIA H100 / A100) | `256` to `512` |

---

## 🚀 Quick Usage Example (PyTorch)

```python
import torch
from zerocopy_stream import ZeroCopyStreamDataLoader

# Mode A: Automatic Auto-Tuning (Detects System RAM & GPU VRAM)
dataloader = ZeroCopyStreamDataLoader(
    dataset_name="HuggingFaceFW/fineweb-edu",
    buffer_size_gb="auto",
    batch_size="auto",
    zero_disk=True
)

device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model = MyTransformerModel().to(device)
optimizer = torch.optim.AdamW(model.parameters(), lr=1e-4)

for step, batch in enumerate(dataloader):
    input_ids = torch.tensor(batch["input_ids"]).to(device)
    outputs = model(input_ids, labels=input_ids)
    loss = outputs.loss
    
    optimizer.zero_grad()
    loss.backward()
    optimizer.step()
```

---

# 🇪🇸 DOCUMENTACIÓN EN ESPAÑOL

## Resumen Ejecutivo
**ZeroCopy-Stream SDK** es un motor de ingesta de datos de ultra-alto rendimiento diseñado para eliminar completamente el almacenamiento en disco local durante el pre-entrenamiento de modelos de lenguaje (LLMs, Transformers, PyTorch, DeepSpeed, Megatron-LM).

Los pipelines de entrenamiento tradicionales requieren descargar y almacenar Terabytes de archivos `.parquet` o `.arrow` en discos NVMe RAID costosos, generando:
1. **Altos Costos de Almacenamiento**: Fortunas pagadas en discos persistentes NVMe en la nube (AWS EBS, GCP).
2. **Degradación Física del Disco**: Destrucción de la vida útil del SSD por exceso de escrituras ($TBW$).
3. **Cuellos de Botella PCIe I/O**: Las GPUs se quedan inactivas esperando a que el disco lea archivos.

**ZeroCopy-Stream SDK** transmite los datos directamente desde sockets de red (Hugging Face, S3) a un **Buffer Circular Sin Bloqueos en RAM (DDR5 / HBM)** mediante mapeo de memoria zero-copy (`VirtualAlloc` / `mmap`), procesando Terabytes con **0 Bytes escritos en el disco local**.

---

## 📋 Requisitos e Instalación

### Requisitos del Sistema
- **Sistema Operativo**: Windows 10/11, Linux (Ubuntu 22.04+), o macOS.
- **Python**: Python 3.10 o superior.
- **Compilador C++**: Clang 17+, GCC 13+, o MSVC 2022 (Soporte C++23).

### Dependencias de Python
```bash
pip install torch datasets huggingface_hub pyarrow psutil
```

---

## 🔑 Autenticación con Token de Hugging Face

* **Datasets Públicos** (ej. `FineWeb-Edu`, `OpenWebMath`): **No requieren token**.
* **Datasets Privados o Restringidos** (ej. `meta-llama/Llama-3`): **Requieren Token de Acceso**.

### Opción A: Vía CLI de Hugging Face (Recomendado)
```bash
huggingface-cli login
```

### Opción B: Vía Variable de Entorno
**Windows PowerShell**:
```powershell
$env:HF_TOKEN="hf_TuTokenDeHuggingFaceAqui"
```
**Linux / macOS**:
```bash
export HF_TOKEN="hf_TuTokenDeHuggingFaceAqui"
```

### Opción C: Parámetro Directo en Python
```python
from zerocopy_stream import ZeroCopyStreamDataLoader

dataloader = ZeroCopyStreamDataLoader(
    dataset_name="meta-llama/Llama-3-Dataset",
    hf_token="hf_TuTokenDeHuggingFaceAqui",
    batch_size="auto"
)
```

---

## ⚙️ Configuración de Parámetros y Ajuste de Hardware

Tanto `buffer_size_gb` como `batch_size` son **parámetros totalmente variables**. Puedes pasar valores exactos o usar `"auto"` para que el SDK detecte tu hardware y ajuste los mejores valores automáticamente.

### 1. `buffer_size_gb` (Tamaño del Buffer Circular en RAM)
$$\text{Buffer Size (GB)} \approx \text{RAM Total del Sistema} \times 0.30$$

| Memoria RAM en el Sistema | Entorno de Hardware | `buffer_size_gb` Recomendado |
| :--- | :--- | :--- |
| **16 GB RAM** | APU (Ryzen 5 8600G) / Laptop | `2.0` a `4.0` GB |
| **32 GB RAM** | Computadora de Escritorio | `8.0` a `12.0` GB |
| **64 GB - 128 GB RAM**| Estación de Trabajo de IA | `16.0` a `32.0` GB |
| **256 GB - 1 TB+ RAM**| Clúster de Servidores (H100 / A100) | `64.0` a `128.0` GB |

### 2. `batch_size` (Lote de Entrenamiento por Paso)
$$\text{Batch Size} = \frac{\text{VRAM Disponible en GPU}}{\text{Memoria del Modelo por Muestra} \times \text{Largo de Secuencia}}$$

| VRAM en GPU | `batch_size` Recomendado (Secuencia = 2048) |
| :--- | :--- |
| **8 GB VRAM** (RTX 3060) | `8` a `16` |
| **16 GB VRAM** (RTX 4060 Ti) | `32` a `48` |
| **24 GB VRAM** (RTX 3090 / 4090) | `64` a `128` |
| **80 GB VRAM** (NVIDIA H100 / A100) | `256` a `512` |

---

## 🚀 Ejemplo Rápido de Uso (PyTorch)

```python
import torch
from zerocopy_stream import ZeroCopyStreamDataLoader

# Auto-Tuning Automático (Detecta RAM y VRAM de la GPU)
dataloader = ZeroCopyStreamDataLoader(
    dataset_name="HuggingFaceFW/fineweb-edu",
    buffer_size_gb="auto",
    batch_size="auto",
    zero_disk=True
)

device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model = MiModeloTransformer().to(device)
optimizer = torch.optim.AdamW(model.parameters(), lr=1e-4)

for step, batch in enumerate(dataloader):
    input_ids = torch.tensor(batch["input_ids"]).to(device)
    outputs = model(input_ids, labels=input_ids)
    loss = outputs.loss
    
    optimizer.zero_grad()
    loss.backward()
    optimizer.step()
```

---

### Author & License / Autor y Licencia
* **Creator & Lead Architect / Creador y Arquitecto Principal**: Leandro Emanuel Timberini  
* **Location / Ubicación**: Ituzaingó, Buenos Aires, Argentina  
* **License / Licencia**: Dual AGPL-3.0 / Enterprise Commercial License  
