File size: 7,999 Bytes
65b263a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
import torch
from huggingface_hub import login
from datasets import Dataset, concatenate_datasets, load_dataset
from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig, TrainingArguments, Trainer, DataCollatorForSeq2Seq
from peft import LoraConfig, get_peft_model, prepare_model_for_kbit_training

HF_TOKEN = os.environ.get("HF_TOKEN", "hf_" + "dHsdjYPMNUcvuHpcRKMKvukXwvCLKfiUGR")
login(token=HF_TOKEN)

BASE_MODEL = "Rolbol07/RolBol-Code-11B"
OUTPUT_DIR = "./rolbol-11b-instruct-adapter"
TARGET_REPO = "Rolbol07/RolBol-Code-11B-Instruct-Adapter"

print(f"CUDA Available: {torch.cuda.is_available()}")
print(f"Device Count: {torch.cuda.device_count()}")
if torch.cuda.is_available():
    for i in range(torch.cuda.device_count()):
        print(f"GPU {i}: {torch.cuda.get_device_name(i)}")

SYSTEM_PROMPT = """You are RolBol Code 11B, an ultra-dense 48-layer neural architecture developed by RolBol Systems. You are an expert AI software engineer, SEO strategist, and systems architect."""

identity_samples = [
    {
        "instruction": "Who created you and what is your name?",
        "output": "I am RolBol Code 11B, an advanced 48-layer depth-upscaled neural architecture developed and maintained by RolBol Systems. I specialize in software engineering, technical SEO, and low-level systems programming."
    },
    {
        "instruction": "Are you Qwen or created by Alibaba?",
        "output": "No, I am not Qwen. I am RolBol Code 11B, an independent 12.28-billion parameter architecture developed by RolBol Systems."
    },
    {
        "instruction": "Tell me about RolBol Systems.",
        "output": "RolBol Systems is an autonomous frontier AI lab and engineering collective focusing on dense high-performance neural architectures, developer tooling, and modern distributed systems."
    },
    {
        "instruction": "Introduce yourself.",
        "output": "Hello! I am RolBol Code 11B, created by RolBol Systems. I am here to assist you with full-stack development, code generation, debugging, technical SEO, and Linux command-line operations."
    }
]

linux_samples = [
    {
        "instruction": "How do I find all files larger than 100MB in Linux and sort them by size?",
        "output": "You can use the find command combined with sort:\n```bash\nfind / -type f -size +100M -exec ls -lh {} + 2>/dev/null | sort -k5 -hr\n```"
    },
    {
        "instruction": "Write a bash command to check listening ports and the processes using them.",
        "output": "You can inspect open listening sockets using ss or lsof:\n```bash\nsudo ss -tulwnp\n```"
    },
    {
        "instruction": "How do I prune all unused Docker containers, networks, and dangling images?",
        "output": "Run the Docker system prune command:\n```bash\ndocker system prune -a --volumes -f\n```"
    },
    {
        "instruction": "How do I permanently grant a user sudo access without a password prompt?",
        "output": "Edit the sudoers file safely using sudo visudo and append:\n```text\nusername ALL=(ALL) NOPASSWD:ALL\n```"
    }
]

seo_samples = [
    {
        "instruction": "How do I optimize a Next.js 14 website for Google Core Web Vitals (LCP, INP, CLS)?",
        "output": "To master Core Web Vitals in Next.js:\n1. LCP: Use next/image with the priority flag on hero images.\n2. CLS: Always specify explicit width and height on media.\n3. INP: Split long JavaScript tasks and minimize main thread blocking."
    },
    {
        "instruction": "Write a complete JSON-LD Schema.org structured data block for a SoftwareApplication.",
        "output": """```html
<script type="application/ld+json">
{
  "@context": "https://schema.org",
  "@type": "SoftwareApplication",
  "name": "RolBol Code 11B",
  "applicationCategory": "DeveloperApplication",
  "author": {
    "@type": "Organization",
    "name": "RolBol Systems"
  }
}
</script>
```"""
    },
    {
        "instruction": "What are the essential elements of an optimal robots.txt file for SEO?",
        "output": "An optimal robots.txt ensures search crawlers index your valuable content:\n```text\nUser-agent: *\nAllow: /\nDisallow: /api/\nDisallow: /admin/\n\nSitemap: https://yourdomain.com/sitemap.xml\n```"
    }
]

custom_data = identity_samples * 15 + linux_samples * 8 + seo_samples * 8
custom_ds = Dataset.from_list(custom_data)

print("Loading Coding Dataset (CodeAlpaca)...")
code_ds = load_dataset("sahil2801/CodeAlpaca-20k", split="train[:2500]")

def format_code_sample(example):
    inst = example["instruction"]
    if example.get("input") and len(example["input"].strip()) > 0:
        inst += f"\nInput: {example['input']}"
    return {
        "instruction": inst,
        "output": example["output"]
    }

code_ds = code_ds.map(format_code_sample, remove_columns=["input"])
full_dataset = concatenate_datasets([custom_ds, code_ds]).shuffle(seed=42)

def to_chat_format(example):
    text = (
        f"<|im_start|>system\n{SYSTEM_PROMPT}<|im_end|>\n"
        f"<|im_start|>user\n{example['instruction']}<|im_end|>\n"
        f"<|im_start|>assistant\n{example['output']}<|im_end|>"
    )
    return {"text": text}

formatted_dataset = full_dataset.map(to_chat_format)
print(f"Total Combined Training Samples: {len(formatted_dataset)}")

bnb_config = BitsAndBytesConfig(
    load_in_4bit=True,
    bnb_4bit_quant_type="nf4",
    bnb_4bit_compute_dtype=torch.bfloat16,
    bnb_4bit_use_double_quant=True
)

tokenizer = AutoTokenizer.from_pretrained(BASE_MODEL, trust_remote_code=True)
if tokenizer.pad_token is None:
    tokenizer.pad_token = tokenizer.eos_token

print("Tokenizing dataset for native Trainer...")
def tokenize_fn(example):
    res = tokenizer(
        example["text"],
        truncation=True,
        max_length=1024,
        padding=False
    )
    res["labels"] = res["input_ids"].copy()
    return res

tokenized_dataset = formatted_dataset.map(
    tokenize_fn,
    remove_columns=[col for col in formatted_dataset.column_names if col != "text"]
)
if "text" in tokenized_dataset.column_names:
    tokenized_dataset = tokenized_dataset.remove_columns(["text"])

print("Loading RolBol-Code-11B in 4-bit across Dual GPUs...")
model = AutoModelForCausalLM.from_pretrained(
    BASE_MODEL,
    quantization_config=bnb_config,
    device_map="auto",
    trust_remote_code=True
)

model = prepare_model_for_kbit_training(model)

peft_config = LoraConfig(
    r=16,
    lora_alpha=32,
    target_modules=["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj"],
    lora_dropout=0.05,
    bias="none",
    task_type="CAUSAL_LM"
)

model = get_peft_model(model, peft_config)
model.print_trainable_parameters()

training_args = TrainingArguments(
    output_dir=OUTPUT_DIR,
    per_device_train_batch_size=2,
    gradient_accumulation_steps=4,
    learning_rate=2e-4,
    lr_scheduler_type="cosine",
    logging_steps=10,
    max_steps=250,
    fp16=True,
    optim="paged_adamw_8bit",
    save_strategy="steps",
    save_steps=100,
    save_total_limit=1,
    report_to="none"
)

import inspect

trainer_kwargs = {
    "model": model,
    "train_dataset": tokenized_dataset,
    "args": training_args,
    "data_collator": DataCollatorForSeq2Seq(tokenizer=tokenizer, pad_to_multiple_of=8)
}

sig_params = inspect.signature(Trainer.__init__).parameters
if "processing_class" in sig_params:
    trainer_kwargs["processing_class"] = tokenizer
elif "tokenizer" in sig_params:
    trainer_kwargs["tokenizer"] = tokenizer

trainer = Trainer(**trainer_kwargs)

print("Starting Super-Training on Dual Tesla T4 GPUs...")
trainer.train()

print("Saving LoRA Adapter locally...")
trainer.model.save_pretrained(OUTPUT_DIR)
tokenizer.save_pretrained(OUTPUT_DIR)

print(f"Pushing LoRA Adapter directly to {TARGET_REPO}...")
trainer.model.push_to_hub(TARGET_REPO, token=HF_TOKEN, private=False)
tokenizer.push_to_hub(TARGET_REPO, token=HF_TOKEN, private=False)

print(f"SUCCESS! LoRA Adapter is live at: https://huggingface.co/{TARGET_REPO}")