File size: 17,888 Bytes
39650ce
333f111
 
39650ce
 
333f111
39650ce
 
333f111
 
 
 
39650ce
333f111
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
435c70a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
333f111
 
 
 
 
 
435c70a
 
 
 
 
333f111
 
 
 
 
 
 
 
 
 
 
 
 
39650ce
 
333f111
 
 
 
 
 
 
 
 
39650ce
333f111
39650ce
333f111
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39650ce
 
 
333f111
39650ce
 
 
 
333f111
 
 
 
 
 
39650ce
333f111
39650ce
 
333f111
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39650ce
333f111
 
 
 
 
 
 
39650ce
333f111
 
 
 
 
39650ce
333f111
39650ce
 
333f111
39650ce
 
 
333f111
 
 
39650ce
333f111
39650ce
333f111
 
39650ce
333f111
 
 
 
 
 
 
 
39650ce
 
333f111
 
 
 
39650ce
333f111
39650ce
 
333f111
 
39650ce
 
333f111
39650ce
 
 
333f111
39650ce
 
333f111
 
39650ce
 
 
 
333f111
 
 
 
39650ce
7d5010c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
333f111
 
 
39650ce
 
 
 
 
 
205f509
 
 
 
 
 
 
 
95e4da1
 
 
 
 
205f509
 
 
 
 
 
 
 
 
 
 
 
 
 
95e4da1
 
 
 
 
205f509
 
 
333f111
205f509
 
 
 
 
 
 
 
 
 
 
39650ce
205f509
333f111
 
5c68696
39650ce
333f111
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39650ce
333f111
 
 
 
 
39650ce
 
 
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
"""
Zen Training Space - Unified Training for All Zen Models
Train any Zen model with any dataset combination from HuggingFace
"""

import os
import gradio as gr
import torch
from transformers import AutoModel, AutoTokenizer, AutoProcessor, TrainingArguments, Trainer
from datasets import load_dataset, concatenate_datasets
import json
from typing import List, Dict

# Model configurations
MODELS = {
    "Language Models": {
        "zen-nano-0.6b": {
            "hf_id": "zenlm/zen-nano-0.6b",
            "type": "language",
            "size": "0.6B",
            "context": "32K"
        },
        "zen-eco-4b-instruct": {
            "hf_id": "zenlm/zen-eco-4b-instruct",
            "type": "language",
            "size": "4B",
            "context": "32K"
        },
        "zen-eco-4b-agent": {
            "hf_id": "zenlm/zen-eco-4b-agent",
            "type": "language",
            "size": "4B",
            "context": "32K"
        },
        "zen-omni-7b": {
            "hf_id": "zenlm/zen-omni-7b",
            "type": "language",
            "size": "7B",
            "context": "32K"
        },
        "zen-coder-14b": {
            "hf_id": "zenlm/zen-coder-14b",
            "type": "language",
            "size": "14B",
            "context": "128K"
        },
        "zen-next-32b": {
            "hf_id": "zenlm/zen-next-32b",
            "type": "language",
            "size": "32B",
            "context": "32K"
        },
    },
    "Vision-Language Models": {
        "zen-vl-4b-instruct": {
            "hf_id": "zenlm/zen-vl-4b-instruct",
            "type": "vision-language",
            "size": "4B",
            "context": "32K"
        },
        "zen-vl-8b-instruct": {
            "hf_id": "zenlm/zen-vl-8b-instruct",
            "type": "vision-language",
            "size": "8B",
            "context": "32K"
        },
        "zen-vl-30b-instruct": {
            "hf_id": "zenlm/zen-vl-30b-instruct",
            "type": "vision-language",
            "size": "30B",
            "context": "32K"
        },
    }
}

# Dataset configurations
DATASETS = {
    "Agent Training": {
        "ADP - AgentTuning OS": {
            "hf_id": "neulab/agent-data-collection",
            "config": "agenttuning_os",
            "size": "~5k samples"
        },
        "ADP - AgentTuning KG": {
            "hf_id": "neulab/agent-data-collection",
            "config": "agenttuning_kg",
            "size": "~5k samples"
        },
        "ADP - AgentTuning DB": {
            "hf_id": "neulab/agent-data-collection",
            "config": "agenttuning_db",
            "size": "~5k samples"
        },
        "ADP - Synatra": {
            "hf_id": "neulab/agent-data-collection",
            "config": "synatra",
            "size": "99k samples"
        },
        "ADP - Code Feedback": {
            "hf_id": "neulab/agent-data-collection",
            "config": "code_feedback",
            "size": "66k samples"
        },
        "ADP - Go Browse": {
            "hf_id": "neulab/agent-data-collection",
            "config": "go-browse-wa",
            "size": "27k samples"
        },
    },
    "Function Calling": {
        "xLAM Function Calling 60k": {
            "hf_id": "Salesforce/xlam-function-calling-60k",
            "config": None,
            "size": "60k samples"
        },
    },
    "Coding Datasets": {
        "Magicoder-OSS-Instruct": {
            "hf_id": "ise-uiuc/Magicoder-OSS-Instruct-75K",
            "config": None,
            "size": "75k code samples"
        },
        "CodeFeedback-Filtered": {
            "hf_id": "m-a-p/CodeFeedback-Filtered-Instruction",
            "config": None,
            "size": "157k code samples"
        },
        "Evol-Instruct-Code": {
            "hf_id": "nickrosh/Evol-Instruct-Code-80k-v1",
            "config": None,
            "size": "80k evolved code"
        },
    },
    "Advanced Agentic": {
        "AgentInstruct": {
            "hf_id": "microsoft/orca-agentinstruct-1M-v1",
            "config": None,
            "size": "1M agent samples"
        },
        "ToolBench": {
            "hf_id": "ToolBench/ToolBench",
            "config": None,
            "size": "16k tool use"
        },
        "WebArena": {
            "hf_id": "neulab/agent-data-collection",
            "config": "nnetnav-wa",
            "size": "~2k web agent"
        },
    },
    "Instruction Tuning": {
        "Alpaca": {
            "hf_id": "tatsu-lab/alpaca",
            "config": None,
            "size": "52k samples"
        },
        "OpenOrca": {
            "hf_id": "Open-Orca/OpenOrca",
            "config": None,
            "size": "4.2M reasoning"
        },
    }
}

def train_model(
    model_name: str,
    selected_datasets: List[str],
    max_samples: int,
    epochs: int,
    batch_size: int,
    learning_rate: float,
    output_repo: str
):
    """Main training function"""
    
    try:
        logs = []
        
        def log(msg):
            print(msg)
            logs.append(msg)
            yield "\n".join(logs)
        
        yield from log("=" * 80)
        yield from log("๐Ÿง˜ ZEN TRAINING SPACE")
        yield from log("=" * 80)
        yield from log("")
        
        # GPU info
        yield from log(f"๐ŸŽฎ GPU Available: {torch.cuda.is_available()}")
        if torch.cuda.is_available():
            yield from log(f"   Device: {torch.cuda.get_device_name(0)}")
            yield from log(f"   Memory: {torch.cuda.get_device_properties(0).total_memory / 1e9:.1f}GB")
        yield from log("")
        
        # Find model config
        # Handle both "Category / ModelName" and "ModelName" formats
        if " / " in model_name:
            model_short_name = model_name.split(" / ")[1]
        else:
            model_short_name = model_name
        
        model_config = None
        for category in MODELS.values():
            if model_short_name in category:
                model_config = category[model_short_name]
                break
        
        if not model_config:
            yield from log(f"โŒ Model {model_short_name} not found")
            return
        
        yield from log(f"๐Ÿ“ฆ Loading model: {model_short_name}")
        yield from log(f"   HF ID: {model_config['hf_id']}")
        yield from log(f"   Size: {model_config['size']}")
        yield from log(f"   Type: {model_config['type']}")
        
        # Load model
        model = AutoModel.from_pretrained(
            model_config['hf_id'],
            torch_dtype=torch.bfloat16,
            device_map="auto",
            trust_remote_code=True
        )
        
        if model_config['type'] == "vision-language":
            processor = AutoProcessor.from_pretrained(model_config['hf_id'])
        else:
            processor = AutoTokenizer.from_pretrained(model_config['hf_id'])
        
        yield from log("โœ… Model loaded")
        yield from log("")
        
        # Load datasets
        yield from log("๐Ÿ“š Loading datasets...")
        all_datasets = []
        
        for dataset_name in selected_datasets:
            # Handle both "Category / DatasetName" and "DatasetName" formats
            if " / " in dataset_name:
                dataset_short_name = dataset_name.split(" / ", 1)[1]
            else:
                dataset_short_name = dataset_name
            
            # Find dataset config
            dataset_config = None
            for category in DATASETS.values():
                if dataset_short_name in category:
                    dataset_config = category[dataset_short_name]
                    break
            
            if not dataset_config:
                yield from log(f"โš ๏ธ  Dataset {dataset_short_name} not found, skipping")
                continue
            
            yield from log(f"   Loading: {dataset_name}")
            yield from log(f"   HF ID: {dataset_config['hf_id']}")
            
            try:
                if dataset_config['config']:
                    ds = load_dataset(
                        dataset_config['hf_id'],
                        dataset_config['config'],
                        split="train",
                        streaming=True
                    )
                else:
                    ds = load_dataset(
                        dataset_config['hf_id'],
                        split="train",
                        streaming=True
                    )
                
                # Take limited samples
                samples = []
                for i, example in enumerate(ds):
                    if i >= max_samples // len(selected_datasets):
                        break
                    samples.append(example)
                
                all_datasets.extend(samples)
                yield from log(f"   โœ… Loaded {len(samples)} samples")
                
            except Exception as e:
                yield from log(f"   โŒ Error: {e}")
        
        yield from log(f"\nโœ… Total samples loaded: {len(all_datasets)}")
        yield from log("")
        
        # Training setup
        yield from log("โš™๏ธ  Training Configuration:")
        yield from log(f"   Epochs: {epochs}")
        yield from log(f"   Batch Size: {batch_size}")
        yield from log(f"   Learning Rate: {learning_rate}")
        yield from log(f"   Samples: {len(all_datasets)}")
        yield from log(f"   Output: {output_repo}")
        yield from log("")
        
        training_args = TrainingArguments(
            output_dir="./training-output",
            num_train_epochs=epochs,
            per_device_train_batch_size=batch_size,
            learning_rate=learning_rate,
            logging_steps=10,
            save_steps=100,
            bf16=True,
            push_to_hub=True,
            hub_model_id=output_repo,
            report_to="tensorboard",
        )
        
        # Create trainer
        trainer = Trainer(
            model=model,
            args=training_args,
            train_dataset=all_datasets if len(all_datasets) > 0 else None,
        )
        
        # Train!
        yield from log("๐Ÿ”ฅ TRAINING STARTED")
        yield from log("=" * 80)
        
        result = trainer.train()
        
        yield from log("")
        yield from log("=" * 80)
        yield from log("โœ… TRAINING COMPLETED!")
        yield from log("=" * 80)
        yield from log(f"๐Ÿ“Š Final Loss: {result.training_loss:.4f}")
        
        # Generate model card with dataset info
        yield from log("")
        yield from log("๐Ÿ“ Generating model card...")
        
        from datetime import datetime
        
        # Build dataset info for model card
        dataset_info = []
        dataset_hf_ids = []
        for dataset_name in selected_datasets:
            if " / " in dataset_name:
                dataset_short_name = dataset_name.split(" / ", 1)[1]
            else:
                dataset_short_name = dataset_name
            
            for category in DATASETS.values():
                if dataset_short_name in category:
                    ds_config = category[dataset_short_name]
                    dataset_info.append(f"- [{dataset_short_name}](https://huggingface.co/datasets/{ds_config['hf_id']}) ({ds_config['size']})")
                    dataset_hf_ids.append(ds_config['hf_id'])
                    break
        
        model_card = f"""---
language:
- en
license: apache-2.0
tags:
- zen
- vision-language
- function-calling
- agent
base_model: {model_config['hf_id']}
datasets:
{chr(10).join([f"- {hf_id}" for hf_id in dataset_hf_ids])}
---

# {output_repo.split('/')[-1]}

Fine-tuned from [{model_config['hf_id']}](https://huggingface.co/{model_config['hf_id']}) using the Zen Training Space.

## Training Details

### Base Model
- **Model**: {model_short_name}
- **Size**: {model_config['size']} parameters
- **Type**: {model_config['type']}
- **Base HF ID**: [{model_config['hf_id']}](https://huggingface.co/{model_config['hf_id']})

### Datasets Used
{chr(10).join(dataset_info)}

### Training Configuration
- **Total Samples**: {len(all_datasets):,}
- **Epochs**: {epochs}
- **Batch Size**: {batch_size}
- **Learning Rate**: {learning_rate}
- **Precision**: bfloat16
- **Final Training Loss**: {result.training_loss:.4f}
- **Training Date**: {datetime.now().strftime('%Y-%m-%d %H:%M:%S UTC')}

### Hardware
- **GPU**: NVIDIA A10G (24GB)
- **Platform**: HuggingFace Spaces

## Usage

```python
from transformers import AutoModel, AutoProcessor

model = AutoModel.from_pretrained("{output_repo}", trust_remote_code=True)
processor = AutoProcessor.from_pretrained("{output_repo}")

# Your inference code here
```

## Training Space

This model was trained using the [Zen Training Space](https://huggingface.co/spaces/zeekay/zen-training), 
a unified platform for training all Zen AI models.

## Citation

```bibtex
@misc{{{output_repo.replace('/', '_').replace('-', '_')},
  author = {{Zen AI}},
  title = {{{output_repo.split('/')[-1]}}},
  year = {{2025}},
  publisher = {{HuggingFace}},
  url = {{https://huggingface.co/{output_repo}}}
}}
```

---

*Trained with โค๏ธ using [Zen Training Space](https://huggingface.co/spaces/zeekay/zen-training)*
"""
        
        # Save model card
        import os
        os.makedirs("./training-output", exist_ok=True)
        with open("./training-output/README.md", "w") as f:
            f.write(model_card)
        
        yield from log("โœ… Model card generated")
        yield from log(f"โ˜๏ธ  Model uploaded to: {output_repo}")
        yield from log("")
        yield from log("๐ŸŽ‰ SUCCESS!")
        
    except Exception as e:
        yield from log(f"\nโŒ ERROR: {str(e)}")
        import traceback
        yield from log(f"\n{traceback.format_exc()}")

# Custom CSS for Inter font and branding
custom_css = """
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap');

* {
    font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif !important;
}

body, .gradio-container {
    background-color: #000 !important;
    color: #fff !important;
}

.logo-header {
    display: flex;
    align-items: center;
    gap: 16px;
    margin-bottom: 24px;
}

.logo-header img {
    height: 48px;
    width: auto;
}

h1, h2, h3, h4 {
    font-weight: 600 !important;
    color: #fff !important;
}

p {
    color: #ccc !important;
}
"""

# Build Gradio Interface
with gr.Blocks(title="Zen Training Space", css=custom_css, theme=gr.themes.Soft()) as demo:
    with gr.Row(elem_classes="logo-header"):
        gr.HTML("""
        <div style="display: flex; align-items: center; gap: 16px;">
            <img src="https://zenlm.org/logo.png" alt="Zen LM" style="height: 48px; width: auto;">
            <div>
                <h1 style="margin: 0; font-size: 28px; font-weight: 600;">Zen Training Space</h1>
                <p style="margin: 0; color: #666; font-size: 16px;">Unified Training Platform for All Zen Models</p>
            </div>
        </div>
        """)
    
    gr.Markdown("""
    Train any Zen model with any dataset combination from HuggingFace.
    All datasets are loaded directly from HF - no local storage needed!
    """)
    
    with gr.Row():
        with gr.Column(scale=1):
            gr.Markdown("### 1. Select Model")
            
            model_choice = gr.Dropdown(
                choices=[
                    *[f"{cat} / {model}" for cat in MODELS for model in MODELS[cat]]
                ],
                label="Model",
                value="Vision-Language Models / zen-vl-4b-instruct"
            )
            
            gr.Markdown("### 2. Select Datasets")
            
            dataset_choices = gr.CheckboxGroup(
                choices=[
                    *[f"{cat} / {ds}" for cat in DATASETS for ds in DATASETS[cat]]
                ],
                label="Datasets",
                value=[
                    "Agent Training / ADP - Synatra",
                    "Function Calling / xLAM Function Calling 60k"
                ]
            )
            
            gr.Markdown("### 3. Training Config")
            
            max_samples = gr.Slider(100, 100000, value=10000, step=100, label="Max Samples")
            epochs = gr.Slider(1, 10, value=3, step=1, label="Epochs")
            batch_size = gr.Slider(1, 8, value=1, step=1, label="Batch Size")
            learning_rate = gr.Number(value=2e-5, label="Learning Rate")
            
            output_repo = gr.Textbox(
                value="zenlm/zen-vl-4b-agent-custom",
                label="Output Repository (HuggingFace)"
            )
            
            train_btn = gr.Button("๐Ÿš€ Start Training", variant="primary", size="lg")
        
        with gr.Column(scale=2):
            gr.Markdown("### Training Logs")
            output = gr.Textbox(label="", lines=35, max_lines=50, show_label=False)
    
    train_btn.click(
        train_model,
        inputs=[
            model_choice,
            dataset_choices,
            max_samples,
            epochs,
            batch_size,
            learning_rate,
            output_repo
        ],
        outputs=output
    )
    
    gr.Markdown("""
    ---
    ### ๐Ÿ“Š Available Models
    - **Language**: nano (0.6B), eco (4B), omni (7B), coder (14B), next (32B)
    - **Vision-Language**: zen-vl (4B, 8B, 30B)
    
    ### ๐Ÿ“š Available Datasets
    - **Agent Training**: ADP (220k+ trajectories across 15+ configs)
    - **Function Calling**: xLAM (60k high-quality examples)
    - **Instruction**: Alpaca (52k samples)
    
    ### ๐Ÿ’ฐ Cost Estimates (HF Pro GPU)
    - 4B model: $3-5 for 10k samples
    - 8B model: $8-12 for 10k samples
    - 32B model: $30-50 for 10k samples
    """)

if __name__ == "__main__":
    demo.launch(server_name="0.0.0.0", server_port=7860)