File size: 17,351 Bytes
9599c8e
33ff5b3
9599c8e
 
33ff5b3
 
 
4224302
dbb0ed0
92820c1
7c75ddd
33ff5b3
9599c8e
33ff5b3
 
 
7c75ddd
 
33ff5b3
 
 
 
9599c8e
7c75ddd
61fcbc1
9599c8e
 
ca12908
 
 
 
9599c8e
33ff5b3
 
572dfb0
 
 
 
33ff5b3
4224302
 
 
dbb0ed0
4224302
33ff5b3
 
7c75ddd
 
 
 
 
 
 
 
 
 
 
 
b9816b5
 
 
 
 
 
 
 
 
 
 
 
 
7c75ddd
 
 
 
 
 
 
 
 
 
 
 
 
33ff5b3
 
7701af4
 
33ff5b3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7c75ddd
33ff5b3
6d6218a
 
9599c8e
 
33ff5b3
 
 
 
7701af4
 
33ff5b3
aea1032
7701af4
 
 
 
 
6d6218a
7c75ddd
 
6d6218a
7c75ddd
6d6218a
7c75ddd
6d6218a
 
7c75ddd
425571a
6d6218a
425571a
7c75ddd
6d6218a
7c75ddd
 
 
6d6218a
7c75ddd
9599c8e
 
33ff5b3
7c75ddd
33ff5b3
 
9599c8e
33ff5b3
7701af4
7c75ddd
33ff5b3
9599c8e
4224302
92820c1
4224302
33ff5b3
 
 
dbb0ed0
33ff5b3
9599c8e
33ff5b3
 
6d6218a
 
92820c1
33ff5b3
92820c1
9599c8e
33ff5b3
 
 
 
 
9599c8e
33ff5b3
 
9599c8e
33ff5b3
92820c1
7701af4
9599c8e
33ff5b3
 
 
 
 
 
 
 
 
 
9599c8e
33ff5b3
92820c1
33ff5b3
dbb0ed0
 
33ff5b3
 
 
 
 
 
 
 
9599c8e
33ff5b3
92820c1
33ff5b3
92820c1
33ff5b3
7701af4
 
 
33ff5b3
 
 
 
7c75ddd
33ff5b3
 
a2dde7c
7c75ddd
33ff5b3
7c75ddd
 
dbb0ed0
 
7c75ddd
33ff5b3
 
 
9599c8e
7c75ddd
4224302
 
 
 
7c75ddd
9599c8e
7c75ddd
 
 
1cb2e39
 
7c75ddd
 
 
 
 
33ff5b3
 
7c75ddd
 
33ff5b3
 
 
 
7701af4
33ff5b3
dbb0ed0
7701af4
572dfb0
0122482
7c75ddd
33ff5b3
 
dbb0ed0
bb40b17
dbb0ed0
7c75ddd
 
 
61fcbc1
33ff5b3
 
 
 
 
7c75ddd
 
33ff5b3
 
7c75ddd
 
33ff5b3
 
7c75ddd
33ff5b3
072b2c1
61fcbc1
33ff5b3
7c75ddd
33ff5b3
 
4224302
33ff5b3
 
 
9599c8e
33ff5b3
7c75ddd
 
aea1032
 
7c75ddd
 
 
 
 
 
aea1032
 
33ff5b3
7c75ddd
9599c8e
7701af4
9599c8e
33ff5b3
 
 
9599c8e
7c75ddd
92820c1
425571a
7c75ddd
425571a
 
92820c1
7c75ddd
425571a
33ff5b3
6d6218a
33ff5b3
92820c1
9599c8e
bb43fa2
33ff5b3
 
92820c1
4224302
33ff5b3
7c75ddd
33ff5b3
572dfb0
9599c8e
33ff5b3
7701af4
9599c8e
33ff5b3
 
9599c8e
33ff5b3
 
7c75ddd
33ff5b3
9599c8e
33ff5b3
 
7701af4
 
33ff5b3
 
7701af4
92820c1
7701af4
33ff5b3
92820c1
9599c8e
33ff5b3
9599c8e
7701af4
9599c8e
33ff5b3
 
7c75ddd
33ff5b3
7701af4
4224302
 
887625f
 
 
 
 
 
 
4224302
 
db13e7d
887625f
7701af4
b9816b5
887625f
 
7701af4
887625f
 
 
7701af4
7c75ddd
887625f
7c75ddd
7701af4
7c75ddd
a2dde7c
887625f
 
7701af4
7c75ddd
7701af4
 
 
 
 
 
33ff5b3
7c75ddd
7701af4
 
33ff5b3
7701af4
 
33ff5b3
887625f
7701af4
 
 
 
 
 
33ff5b3
7701af4
887625f
7701af4
33ff5b3
7701af4
33ff5b3
7c75ddd
7701af4
572dfb0
7701af4
 
33ff5b3
7701af4
33ff5b3
 
7701af4
 
9599c8e
33ff5b3
af9bf03
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
import os
import json
import logging
import threading
import uuid
import time
import sys
import gc
import multiprocessing
import shutil
import math
from datetime import datetime
from concurrent.futures import ThreadPoolExecutor, as_completed
from itertools import chain

import torch
import torch.nn as nn
import torch.nn.functional as F
import gradio as gr
import transformers
import datasets
from dotenv import load_dotenv
from datasets import load_dataset, get_dataset_config_names, IterableDataset
from transformers import AutoModelForCausalLM, AutoTokenizer, TrainingArguments, Trainer, TrainerCallback, AutoConfig, DataCollatorForLanguageModeling
from huggingface_hub import login, whoami, create_repo, upload_folder
import spaces

try:
    load_dotenv()
except:
    pass

transformers.logging.set_verbosity_error()
datasets.logging.set_verbosity_error()
logging.getLogger("transformers").setLevel(logging.CRITICAL)
logging.getLogger("datasets").setLevel(logging.CRITICAL)
logging.getLogger("torch").setLevel(logging.CRITICAL)
logging.basicConfig(level=logging.CRITICAL, stream=sys.stderr)

if torch.cuda.is_available():
    torch.backends.cuda.matmul.allow_tf32 = True
    torch.backends.cudnn.allow_tf32 = True
    torch.backends.cudnn.benchmark = True

JOBS = {}

def activation_quant(x):
    scale = 127.0 / x.abs().max(dim=-1, keepdim=True).values.clamp_(min=1e-5)
    y = (x * scale).round().clamp_(-128, 127) / scale
    return y + x - x.detach()

def weight_quant(w):
    scale = 1.0 / w.abs().mean().clamp_(min=1e-5)
    u = (w * scale).round().clamp_(-1, 1) / scale
    return u + w - w.detach()

class BitLinear(nn.Linear):
    def forward(self, x):
        target_dtype = x.dtype
        
        w = self.weight.to(target_dtype)
        w_quant = weight_quant(w).to(target_dtype)
        
        x_quant = activation_quant(x).to(target_dtype)
        
        if self.bias is not None:
            b = self.bias.to(target_dtype)
        else:
            b = None
            
        return F.linear(x_quant, w_quant, b)

def convert_to_bitnet(model, copy_weights=False):
    for name, module in model.named_children():
        if isinstance(module, nn.Linear):
            bit_linear = BitLinear(module.in_features, module.out_features, module.bias is not None)
            if copy_weights:
                bit_linear.weight.data = module.weight.data.clone()
                if module.bias is not None:
                    bit_linear.bias.data = module.bias.data.clone()
            setattr(model, name, bit_linear)
        else:
            convert_to_bitnet(module, copy_weights=copy_weights)

class JobStatus:
    def __init__(self):
        self.id = str(uuid.uuid4())
        self.status = "INITIALIZING"
        self.progress = 0.0
        self.logs = []
        self.result = None
        self.error = None
        self.created_at = datetime.now().strftime("%H:%M:%S")
        self.repo_url = None

    def add_log(self, message):
        timestamp = datetime.now().strftime("%H:%M:%S")
        self.logs.append(f"[{timestamp}] {message}")
    
    def set_progress(self, val, msg=None):
        self.progress = val
        if msg:
            self.add_log(msg)

class CustomTrainerCallback(TrainerCallback):
    def __init__(self, job_id, hf_token, repo_id):
        self.job_id = job_id
        self.hf_token = hf_token
        self.repo_id = repo_id
    
    def on_step_end(self, args, state, control, **kwargs):
        if self.job_id in JOBS:
            job = JOBS[self.job_id]
            if state.max_steps > 0:
                prog = state.global_step / state.max_steps
                job.progress = 0.1 + (prog * 0.8)
                if state.global_step % 1 == 0:
                    loss = state.log_history[-1].get('loss', 'N/A') if state.log_history else '...'
                    job.add_log(f"Training Step {state.global_step}/{state.max_steps} | Loss: {loss}")
        return control

    def on_save(self, args, state, control, **kwargs):
        if self.job_id in JOBS:
            job = JOBS[self.job_id]
            step = state.global_step
            ckpt_name = f"checkpoint-{step}"
            ckpt_path = os.path.join(args.output_dir, ckpt_name)
            
            job.add_log(f"System: 100-Step Snapshot saved ({ckpt_name})")
            
            def _upload_bg():
                try:
                    upload_folder(
                        folder_path=ckpt_path,
                        path_in_repo=".",
                        repo_id=self.repo_id,
                        token=self.hf_token,
                        commit_message=f"Live Checkpoint Step {step}"
                    )
                    job.add_log(f"Cloud: Synced Checkpoint {step} to Root")
                except:
                    pass

            threading.Thread(target=_upload_bg, daemon=True).start()
        return control

@spaces.GPU(duration=300)
def background_train_task(job_id, hf_token, model_name, new_repo_name, 
                          train_steps, learning_rate, batch_size, datasets_text, 
                          reasoning_mode, c_conf, c_tok, c_gen):
    
    job = JOBS[job_id]
    job.status = "RUNNING"
    job.add_log("System: initializing BitNet Scratch Protocol...")

    try:
        if not hf_token.startswith("hf_"):
            raise ValueError("Invalid Token")

        os.environ["WANDB_DISABLED"] = "true"
        os.environ["HF_TOKEN"] = hf_token
        os.environ["TRANSFORMERS_NO_ADVISORY_WARNINGS"] = "true"
        os.environ["TOKENIZERS_PARALLELISM"] = "true"
        
        login(token=hf_token)
        try:
            username = whoami()["name"]
            full_repo_id = f"{username}/{new_repo_name}"
            create_repo(full_repo_id, token=hf_token, exist_ok=True)
            job.add_log(f"Auth: Verified {username} -> {full_repo_id}")
        except:
            raise Exception("Auth Failed")

        if not hasattr(torch, 'xla'):
            class DummyXLA:
                def __getattr__(self, name):
                    return lambda *args, **kwargs: None
            torch.xla = DummyXLA()

        raw_items = datasets_text.replace('\n', ',').split(',')
        dataset_list = [item.strip() for item in raw_items if item.strip()]

        if reasoning_mode:
            job.add_log("Config: Reasoning Injection Active")
            dataset_list.extend(["gsm8k", "openai/gsm8k"])

        def load_single(ds_name, cfg):
            try:
                ds = load_dataset(ds_name, cfg if cfg else "main", split="train", streaming=True, trust_remote_code=False)
                try:
                    next(iter(ds))
                    return ds
                except:
                    return None
            except:
                return None

        streams = []
        job.set_progress(0.05, "Data: Parallel Stream Connect...")
        
        cpu_count = multiprocessing.cpu_count()
        with ThreadPoolExecutor(max_workers=cpu_count * 2) as executor:
            futures = []
            for ds_name in dataset_list:
                futures.append(executor.submit(load_single, ds_name, None))
            
            for future in as_completed(futures):
                res = future.result()
                if res:
                    streams.append(res)

        if not streams:
            raise Exception("No Data Sources")

        job.set_progress(0.1, f"Data: {len(streams)} Streams Linked")

        tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True, padding_side="left", add_eos_token=True, add_bos_token=True)
        if tokenizer.pad_token is None:
            tokenizer.pad_token = tokenizer.eos_token

        def process_stream_generator():
            iterator = chain.from_iterable(streams)
            batch_buffer = []
            
            for item in iterator:
                try:
                    text = str(item.get("text", item.get("content", str(item))))
                    if len(text) < 5: continue
                    batch_buffer.append(text)
                    
                    if len(batch_buffer) >= 100:
                        encoded_batch = tokenizer(batch_buffer, truncation=True, max_length=2048, padding=False)
                        for input_ids in encoded_batch["input_ids"]:
                            yield {"input_ids": input_ids}
                        batch_buffer = []
                except:
                    continue

        job.set_progress(0.15, "Model: Initializing Architecture & Converting to BitNet...")
        
        torch.cuda.empty_cache()
        gc.collect()

        config = AutoConfig.from_pretrained(model_name, trust_remote_code=True)
        
        original_model = AutoModelForCausalLM.from_config(
            config, 
            trust_remote_code=True,
        )
        
        convert_to_bitnet(original_model, copy_weights=False)
        
        model_size = sum(t.numel() for t in original_model.parameters())
        job.add_log(f"Model Size: {model_size/1000**2:.1f}M Parameters (1.58-bit)")

        output_dir = f"checkpoints/{job_id}"
        
        data_collator = DataCollatorForLanguageModeling(tokenizer=tokenizer, mlm=False)

        training_args = TrainingArguments(
            output_dir=output_dir,
            per_device_train_batch_size=int(batch_size),
            gradient_accumulation_steps=4,
            max_steps=int(train_steps),
            learning_rate=learning_rate,
            optim="adamw_torch_fused" if torch.cuda.is_available() else "adamw_torch",
            logging_steps=1,
            save_strategy="steps",
            save_steps=100,
            save_total_limit=1,
            report_to="none",
            fp16=True if torch.cuda.is_available() else False,
            disable_tqdm=True,
            dataloader_num_workers=4,
            dataloader_pin_memory=True,
            gradient_checkpointing=True,
            torch_compile=False,
            lr_scheduler_type="cosine",
            warmup_ratio=0.1
        )

        dataset_iterable = IterableDataset.from_generator(process_stream_generator)

        trainer = Trainer(
            model=original_model,
            tokenizer=tokenizer,
            train_dataset=dataset_iterable,
            args=training_args,
            data_collator=data_collator,
            callbacks=[CustomTrainerCallback(job_id, hf_token, full_repo_id)]
        )

        job.set_progress(0.2, "Training: BitNet Gradient Descent Initiated...")
        trainer.train()
        trainer.save_model(output_dir)
        tokenizer.save_pretrained(output_dir)
        
        job.set_progress(0.9, "Processing: Finalizing Artifacts...")
        del original_model
        torch.cuda.empty_cache()
        gc.collect()

        def inject_json(content, fname):
            if content and content.strip():
                try:
                    data = json.loads(content)
                    file_path = os.path.join(output_dir, fname)
                    
                    if os.path.exists(file_path):
                        with open(file_path, 'r', encoding='utf-8') as f:
                            try:
                                existing_data = json.load(f)
                                existing_data.update(data)
                                data = existing_data
                            except:
                                pass
                    
                    with open(file_path, 'w', encoding='utf-8') as f:
                        json.dump(data, f, indent=2)
                    job.add_log(f"Config: Overwritten {fname} with user settings")
                except:
                    pass

        inject_json(c_conf, "config.json")
        inject_json(c_tok, "tokenizer_config.json")
        inject_json(c_gen, "generation_config.json")

        job.set_progress(0.95, "Network: Uploading Final BitNet Model...")
        
        upload_folder(
            folder_path=output_dir, 
            path_in_repo=".", 
            repo_id=full_repo_id, 
            token=hf_token,
            commit_message="BitNet Scratch Trained Model"
        )

        job.repo_url = f"https://huggingface.co/{full_repo_id}"
        job.status = "COMPLETED"
        job.set_progress(1.0, "System: Operation Finalized")

    except Exception as e:
        job.status = "FAILED"
        job.error = str(e)
        job.add_log(f"FATAL ERROR: {str(e)}")
        torch.cuda.empty_cache()

def start_training_wrapper(hf_token, model_name, new_repo_name, 
                           train_steps, learning_rate, batch_size, datasets_text, 
                           reasoning_mode, c_conf, c_tok, c_gen):
    
    if not hf_token or not model_name:
        return None, gr.update(selected="launch_tab")

    new_job = JobStatus()
    JOBS[new_job.id] = new_job

    thread = threading.Thread(
        target=background_train_task,
        args=(new_job.id, hf_token, model_name, new_repo_name, 
              train_steps, learning_rate, batch_size, datasets_text, reasoning_mode, c_conf, c_tok, c_gen)
    )
    thread.daemon = True
    thread.start()
    
    return new_job.id, gr.update(selected="monitor_tab")

def get_job_update(job_id):
    if not job_id:
        return "Waiting...", "", 0, "", gr.update(visible=False)

    if job_id not in JOBS:
        return "Not Found", "", 0, "", gr.update(visible=False)
    
    job = JOBS[job_id]
    
    log_text = "\n".join(job.logs)
    
    result_comp = gr.update(visible=False)
    if job.status == "COMPLETED" and job.repo_url:
        result_comp = gr.update(visible=True, value=f"✅ Full Model Published: {job.repo_url}")
    
    return job.status, job.created_at, job.progress, log_text, result_comp

def load_from_url(request: gr.Request):
    try:
        params = request.query_params
        job_id = params.get("job_id")
        if job_id:
            return gr.update(selected="monitor_tab"), job_id
    except:
        pass
    return gr.update(selected="launch_tab"), ""

with gr.Blocks(title="Nucleus Enterprise") as demo:
    with gr.Column():
        gr.Markdown("# ⚛️ NUCLEUS ENTERPRISE")
        gr.Markdown("Autonomous LLM Foundry | V10.0 BitNet Edition")
        
        with gr.Tabs() as main_tabs:
            with gr.TabItem("🚀 LAUNCHPAD", id="launch_tab"):
                with gr.Row():
                    with gr.Column(scale=2):
                        with gr.Row():
                            hf_token = gr.Textbox(label="HuggingFace Token", type="password", value=os.getenv("HF_TOKEN", ""))
                            model_name = gr.Textbox(label="Architecture Config Source", value="Qwen/Qwen2.5-0.5B")
                        
                        repo_name = gr.Textbox(label="Output Repository", value="nucleus-bitnet-v1")
                        datasets = gr.Textbox(label="Datasets (CSV)", value="Salesforce/fineweb_deduplicated", lines=3)
                        
                        reasoning = gr.Checkbox(label="Inject Reasoning (CoT/Math)", value=False)

                    with gr.Column(scale=1):
                        steps = gr.Number(label="Steps", value=100)
                        lr = gr.Number(label="Learning Rate", value=1e-4)
                        batch = gr.Number(label="Batch Size", value=1)

                with gr.Accordion("Advanced Config", open=False):
                    c_conf = gr.Code(label="config.json", language="json")
                    c_tok = gr.Code(label="tokenizer_config.json", language="json")
                    c_gen = gr.Code(label="generation_config.json", language="json")

                btn_launch = gr.Button("INITIALIZE BITNET TRAINING", variant="primary", size="lg")

            with gr.TabItem("📡 TELEMETRY", id="monitor_tab"):
                with gr.Row():
                    job_id_input = gr.Textbox(label="Active Job ID", interactive=True)
                    btn_refresh = gr.Button("Refresh Stream")
                
                with gr.Row():
                    status_out = gr.Textbox(label="Status", interactive=False)
                    time_out = gr.Textbox(label="Start Time", interactive=False)
                    progress_out = gr.Slider(label="Progress", minimum=0, maximum=1)
                
                final_link = gr.Markdown(visible=False)
                logs_out = gr.Code(label="Real-time Kernel Logs", language="shell", interactive=False, lines=15)

    timer = gr.Timer(2000, active=False)

    demo.load(load_from_url, None, [main_tabs, job_id_input]).then(lambda: gr.Timer(active=True), None, timer)

    btn_launch.click(
        start_training_wrapper,
        inputs=[hf_token, model_name, repo_name, steps, lr, batch, datasets, reasoning, c_conf, c_tok, c_gen],
        outputs=[job_id_input, main_tabs]
    ).then(
        None, [job_id_input], None,
        js="(id) => { if (id) { const url = new URL(window.location); url.searchParams.set('job_id', id); window.history.pushState({}, '', url); } return id; }"
    ).then(
        lambda: gr.Timer(active=True), None, timer
    )

    btn_refresh.click(get_job_update, job_id_input, [status_out, time_out, progress_out, logs_out, final_link])
    timer.tick(get_job_update, job_id_input, [status_out, time_out, progress_out, logs_out, final_link])

if __name__ == "__main__":
    demo.launch(ssr_mode=False)