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
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
# TTV-1B Setup Guide

Complete installation and setup instructions for the TTV-1B text-to-video model.

## Prerequisites

### Hardware Requirements

#### Minimum (Inference Only)
- GPU: 8GB VRAM (RTX 3070, RTX 4060 Ti)
- RAM: 16GB
- Storage: 50GB
- OS: Ubuntu 20.04+, Windows 10+, macOS 12+

#### Recommended (Training)
- GPU: 24GB+ VRAM (RTX 4090, A5000, A100)
- RAM: 64GB
- Storage: 500GB SSD
- OS: Ubuntu 22.04 LTS

#### Production (Full Training)
- GPU: 8Γ— A100 80GB
- RAM: 512GB
- Storage: 2TB NVMe SSD
- Network: High-speed interconnect for multi-GPU

### Software Requirements

- Python 3.9, 3.10, or 3.11
- CUDA 11.8+ (for GPU acceleration)
- cuDNN 8.6+
- Git

## Installation

### Step 1: Clone Repository

```bash
git clone https://github.com/yourusername/ttv-1b.git
cd ttv-1b
```

### Step 2: Create Virtual Environment

```bash
# Using venv
python3 -m venv venv
source venv/bin/activate  # Linux/Mac
# or
venv\Scripts\activate  # Windows

# Using conda (alternative)
conda create -n ttv1b python=3.10
conda activate ttv1b
```

### Step 3: Install PyTorch

Choose the appropriate command for your system from https://pytorch.org/get-started/locally/

```bash
# CUDA 11.8 (most common)
pip install torch torchvision --index-url https://download.pytorch.org/whl/cu118

# CUDA 12.1
pip install torch torchvision --index-url https://download.pytorch.org/whl/cu121

# CPU only (not recommended)
pip install torch torchvision
```

### Step 4: Install Dependencies

```bash
pip install -r requirements.txt
```

### Step 5: Verify Installation

```bash
python -c "import torch; print(f'PyTorch {torch.__version__}'); print(f'CUDA available: {torch.cuda.is_available()}')"
```

Expected output:
```
PyTorch 2.1.0
CUDA available: True
```

## Quick Start

### Test the Model

```bash
# Run evaluation script to verify everything works
python evaluate.py
```

This will:
- Create the model
- Count parameters (should be ~1.0B)
- Test forward/backward passes
- Measure inference speed
- Check memory usage

### Generate Your First Video (After Training)

```bash
python inference.py \
    --prompt "A beautiful sunset over mountains" \
    --checkpoint checkpoints/checkpoint_best.pt \
    --output my_first_video.mp4 \
    --steps 50
```

## Preparing Data

### Data Format

The model expects video-text pairs in the following format:

```
data/
β”œβ”€β”€ videos/
β”‚   β”œβ”€β”€ video_0001.mp4
β”‚   β”œβ”€β”€ video_0002.mp4
β”‚   └── ...
└── annotations.json
```

annotations.json:
```json
{
  "video_0001": {
    "caption": "A cat playing with a ball of yarn",
    "duration": 2.0,
    "fps": 8
  },
  "video_0002": {
    "caption": "Sunset over the ocean with waves",
    "duration": 2.0,
    "fps": 8
  }
}
```

### Video Specifications

- Format: MP4, AVI, or MOV
- Resolution: 256Γ—256 (will be resized)
- Frame rate: 8 FPS recommended
- Duration: 2 seconds (16 frames at 8 FPS)
- Codec: H.264 recommended

### Converting Videos

```bash
# Using FFmpeg to convert videos
ffmpeg -i input.mp4 -vf "scale=256:256,fps=8" -t 2 -c:v libx264 output.mp4
```

### Dataset Preparation Script

```python
import json
from pathlib import Path

def create_annotations(video_dir, output_file):
    """Create annotations file from videos"""
    video_dir = Path(video_dir)
    annotations = {}
    
    for video_path in video_dir.glob("*.mp4"):
        video_id = video_path.stem
        annotations[video_id] = {
            "caption": f"Video {video_id}",  # Add actual captions
            "duration": 2.0,
            "fps": 8
        }
    
    with open(output_file, 'w') as f:
        json.dump(annotations, f, indent=2)

# Usage
create_annotations("data/videos", "data/annotations.json")
```

## Training

### Single GPU Training

```bash
python train.py
```

Configuration in train.py:
```python
config = {
    'batch_size': 2,
    'gradient_accumulation_steps': 8,  # Effective batch size = 16
    'learning_rate': 1e-4,
    'num_epochs': 100,
    'mixed_precision': True,
}
```

### Multi-GPU Training (Recommended)

```bash
# Using PyTorch DDP
torchrun --nproc_per_node=8 train.py

# Or using accelerate (better)
accelerate config  # First time setup
accelerate launch train.py
```

### Monitoring Training

```bash
# Install tensorboard
pip install tensorboard

# Run tensorboard
tensorboard --logdir=./checkpoints/logs
```

### Resume from Checkpoint

```python
# In train.py, add:
trainer.load_checkpoint('checkpoints/checkpoint_step_10000.pt')
trainer.train()
```

## Inference

### Basic Inference

```python
from inference import generate_video_from_prompt

video = generate_video_from_prompt(
    prompt="A serene lake with mountains",
    checkpoint_path="checkpoints/best.pt",
    output_path="output.mp4",
    num_steps=50,
    guidance_scale=7.5,
    seed=42  # For reproducibility
)
```

### Batch Inference

```python
from inference import batch_generate

prompts = [
    "A cat playing",
    "Ocean waves",
    "City at night"
]

batch_generate(
    prompts=prompts,
    checkpoint_path="checkpoints/best.pt",
    output_dir="./outputs",
    num_steps=50
)
```

### Advanced Options

```python
# Lower guidance for more creative results
video = generate_video_from_prompt(
    prompt="Abstract art in motion",
    guidance_scale=5.0,  # Lower = more creative
    num_steps=100,        # More steps = higher quality
)

# Fast generation (fewer steps)
video = generate_video_from_prompt(
    prompt="Quick test",
    num_steps=20,  # Faster but lower quality
)
```

## Optimization Tips

### Memory Optimization

1. **Reduce Batch Size**
```python
config['batch_size'] = 1  # Minimum
config['gradient_accumulation_steps'] = 16  # Maintain effective batch size
```

2. **Enable Gradient Checkpointing**
```python
config['gradient_checkpointing'] = True
```

3. **Use Mixed Precision**
```python
config['mixed_precision'] = True  # Always recommended
```

### Speed Optimization

1. **Use Torch Compile** (PyTorch 2.0+)
```python
model = torch.compile(model)
```

2. **Enable cuDNN Benchmarking**
```python
torch.backends.cudnn.benchmark = True
```

3. **Pin Memory**
```python
DataLoader(..., pin_memory=True)
```

## Troubleshooting

### CUDA Out of Memory

```bash
# Reduce batch size
config['batch_size'] = 1

# Enable gradient checkpointing
config['gradient_checkpointing'] = True

# Clear cache
torch.cuda.empty_cache()
```

### Slow Training

```bash
# Check GPU utilization
nvidia-smi

# Increase num_workers
DataLoader(..., num_workers=8)

# Enable mixed precision
config['mixed_precision'] = True
```

### NaN Loss

```python
# Reduce learning rate
config['learning_rate'] = 5e-5

# Enable gradient clipping (already included)
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)

# Check for NaN in data
assert not torch.isnan(videos).any()
```

### Model Not Learning

```python
# Increase learning rate
config['learning_rate'] = 2e-4

# Check data quality
# Verify annotations are correct
# Ensure videos are properly normalized

# Reduce regularization
config['weight_decay'] = 0.001  # Lower weight decay
```

## Performance Benchmarks

### Training Speed (A100 80GB)

| Batch Size | Grad Accum | Eff. Batch | Sec/Batch | Hours/100K steps |
|------------|------------|------------|-----------|------------------|
| 1 | 16 | 16 | 2.5 | 69 |
| 2 | 8 | 16 | 2.5 | 69 |
| 4 | 4 | 16 | 2.7 | 75 |

### Inference Speed

| GPU | FP16 | Steps | Time/Video |
|-----|------|-------|------------|
| A100 80GB | Yes | 50 | 15s |
| RTX 4090 | Yes | 50 | 25s |
| RTX 3090 | Yes | 50 | 35s |

### Memory Usage

| Operation | Batch Size | Memory (GB) |
|-----------|------------|-------------|
| Inference | 1 | 6 |
| Training | 1 | 12 |
| Training | 2 | 24 |
| Training | 4 | 48 |

## Next Steps

1. **Prepare your dataset** - Collect and annotate videos
2. **Start training** - Begin with small dataset to verify
3. **Monitor progress** - Check loss, sample generations
4. **Fine-tune** - Adjust hyperparameters based on results
5. **Evaluate** - Test on held-out validation set
6. **Deploy** - Use for inference on new prompts

## Getting Help

- GitHub Issues: Report bugs and ask questions
- Documentation: Check README.md and ARCHITECTURE.md
- Examples: See example scripts in the repository

## Additional Resources

- [PyTorch Documentation](https://pytorch.org/docs/)
- [Diffusion Models Explained](https://lilianweng.github.io/posts/2021-07-11-diffusion-models/)
- [Attention Is All You Need](https://arxiv.org/abs/1706.03762)
- [DiT Paper](https://arxiv.org/abs/2212.09748)