Newone0 commited on
Commit
44638a2
·
verified ·
1 Parent(s): bc26096

Publish MicroOps-VLM weights, standalone model code, config, and model card

Browse files
Files changed (4) hide show
  1. README.md +52 -0
  2. config.json +38 -0
  3. model.safetensors +3 -0
  4. modeling_microops.py +209 -0
README.md CHANGED
@@ -1,3 +1,55 @@
1
  ---
2
  license: apache-2.0
 
 
 
 
 
 
 
 
 
 
 
3
  ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
  license: apache-2.0
3
+ library_name: pytorch
4
+ pipeline_tag: image-text-to-text
5
+ tags:
6
+ - multimodal
7
+ - vision-language-model
8
+ - tool-calling
9
+ - function-calling
10
+ - structured-outputs
11
+ - json-mode
12
+ - from-scratch
13
+ - cloud-ops
14
  ---
15
+
16
+ # MicroOps-VLM (9.46M Parameters, Trained 100% From Scratch)
17
+
18
+ **MicroOps-VLM** is a compact, educational, domain-specific multimodal Vision-Language Model (~9.46M parameters) built and trained **100% from scratch** on a single NVIDIA T4 GPU (Google Colab Free Tier).
19
+
20
+ It inspects synthetic `64x64` RGB server telemetry dashboards (and text instructions), follows system-prompt policies, outputs strict JSON, and performs tool calling inside a **768-token context window**.
21
+
22
+ ## Model Architecture & Metrics
23
+ - **Parameters:** 9.46M (tied token embedding & LM head)
24
+ - **Context Window:** 768 tokens (Rotary Position Embeddings / RoPE)
25
+ - **LLM Backbone:** 6-layer Causal Transformer (`d_model=320`, `n_heads=8`, `d_ff=864`), RMSNorm, SwiGLU, PyTorch SDPA
26
+ - **Vision Encoder:** 5-layer GroupNorm CNN stem mapping `64x64` RGB telemetry dashboards into 16 visual patch embeddings + MLP projector
27
+ - **Tokenizer:** Custom UTF-8 byte-level + 18 structured control tokens (`vocab_size=288`)
28
+ - **Held-Out Eval (50 unseen samples):**
29
+ - Validation Loss: 0.0009
30
+ - Valid JSON Rate: **100.0% (50/50)**
31
+ - Exact Turn-1 Accuracy: **100.0% (50/50)**
32
+
33
+ ## Limitations & Intended Use
34
+ This model is an educational architecture demo trained on synthetic `64x64` telemetry dashboards and Cloud Ops tool prompts. It is **not** intended for open-world chat, natural photographs, or production infrastructure control.
35
+
36
+ ## Quickstart Usage
37
+ ```python
38
+ from huggingface_hub import hf_hub_download
39
+ import importlib.util
40
+
41
+ mod_path = hf_hub_download(repo_id="Newone0/MicroOps-VLM", filename="modeling_microops.py")
42
+ spec = importlib.util.spec_from_file_location("modeling_microops", mod_path)
43
+ modeling = importlib.util.module_from_spec(spec)
44
+ spec.loader.exec_module(modeling)
45
+
46
+ model, tok, cfg = modeling.from_pretrained_hf("Newone0/MicroOps-VLM", device="cpu")
47
+
48
+ prompt = tok.build_prompt(
49
+ system_prompt="You are MicroOps, an autonomous SRE agent. Tools: restart_service, scale_cluster, create_ticket, query_metrics. Respond with JSON tool calls.",
50
+ user_prompt="Scale cluster in us-west to 5 replicas.",
51
+ has_image=False,
52
+ )
53
+ out_ids = model.generate_turn(prompt, image=None, temperature=0.0)
54
+ print(tok.decode(out_ids))
55
+ ```
config.json ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "context_window": 768,
3
+ "img_size": 64,
4
+ "n_img_tokens": 16,
5
+ "d_model": 320,
6
+ "n_layers": 6,
7
+ "n_heads": 8,
8
+ "d_ff": 864,
9
+ "dropout": 0.05,
10
+ "train_samples": 8000,
11
+ "val_samples": 400,
12
+ "batch_size": 32,
13
+ "epochs": 10,
14
+ "lr": 0.0006,
15
+ "weight_decay": 0.05,
16
+ "ckpt_path": "microops_vlm_scratch.pt",
17
+ "vocab_size": 288,
18
+ "special_tokens": [
19
+ "<|pad|>",
20
+ "<|bos|>",
21
+ "<|eos|>",
22
+ "<|system|>",
23
+ "<|/system|>",
24
+ "<|user|>",
25
+ "<|/user|>",
26
+ "<|assistant|>",
27
+ "<|/assistant|>",
28
+ "<|img_start|>",
29
+ "<|img_patch|>",
30
+ "<|img_end|>",
31
+ "<|tool_call|>",
32
+ "<|/tool_call|>",
33
+ "<|tool_result|>",
34
+ "<|/tool_result|>",
35
+ "<|json|>",
36
+ "<|/json|>"
37
+ ]
38
+ }
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:058fca1ecf098576636a08a2a15d3496d1638b3fa28a0531790ead5fcd17b07a
3
+ size 37835128
modeling_microops.py ADDED
@@ -0,0 +1,209 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import torch
3
+ import torch.nn as nn
4
+ import torch.nn.functional as F
5
+ from huggingface_hub import hf_hub_download
6
+ from safetensors.torch import load_model
7
+
8
+
9
+ class ByteAgentTokenizer:
10
+ SPECIAL_TOKENS = [
11
+ "<|pad|>", "<|bos|>", "<|eos|>",
12
+ "<|system|>", "<|/system|>",
13
+ "<|user|>", "<|/user|>",
14
+ "<|assistant|>", "<|/assistant|>",
15
+ "<|img_start|>", "<|img_patch|>", "<|img_end|>",
16
+ "<|tool_call|>", "<|/tool_call|>",
17
+ "<|tool_result|>", "<|/tool_result|>",
18
+ "<|json|>", "<|/json|>",
19
+ ]
20
+
21
+ def __init__(self):
22
+ self.special_to_id = {tok: i for i, tok in enumerate(self.SPECIAL_TOKENS)}
23
+ self.id_to_special = {i: tok for i, tok in enumerate(self.SPECIAL_TOKENS)}
24
+ self.byte_offset = len(self.SPECIAL_TOKENS)
25
+ self.vocab_size = 288
26
+ self.pad_id = self.special_to_id["<|pad|>"]
27
+ self.bos_id = self.special_to_id["<|bos|>"]
28
+ self.eos_id = self.special_to_id["<|eos|>"]
29
+ self.img_patch_id = self.special_to_id["<|img_patch|>"]
30
+ self.end_assistant_id = self.special_to_id["<|/assistant|>"]
31
+ self.end_tool_call_id = self.special_to_id["<|/tool_call|>"]
32
+
33
+ def encode_text(self, text: str):
34
+ return [self.byte_offset + b for b in text.encode("utf-8")]
35
+
36
+ def decode(self, ids, skip_special=False):
37
+ out, buf = [], bytearray()
38
+ for tid in ids:
39
+ tid = int(tid)
40
+ if self.byte_offset <= tid < self.byte_offset + 256:
41
+ buf.append(tid - self.byte_offset)
42
+ else:
43
+ if buf:
44
+ out.append(buf.decode("utf-8", errors="replace"))
45
+ buf.clear()
46
+ if not skip_special and tid in self.id_to_special and tid != self.pad_id:
47
+ out.append(self.id_to_special[tid])
48
+ if buf:
49
+ out.append(buf.decode("utf-8", errors="replace"))
50
+ return "".join(out)
51
+
52
+ def build_prompt(self, system_prompt: str, user_prompt: str, has_image: bool = False, n_img_tokens: int = 16):
53
+ ids = [self.bos_id, self.special_to_id["<|system|>"]] + self.encode_text(system_prompt) + [self.special_to_id["<|/system|>"]]
54
+ ids += [self.special_to_id["<|user|>"]] + self.encode_text(user_prompt)
55
+ if has_image:
56
+ ids += [self.special_to_id["<|img_start|>"]] + [self.img_patch_id] * n_img_tokens + [self.special_to_id["<|img_end|>"]]
57
+ ids += [self.special_to_id["<|/user|>"], self.special_to_id["<|assistant|>"]]
58
+ return ids
59
+
60
+
61
+ class RMSNorm(nn.Module):
62
+ def __init__(self, dim: int, eps: float = 1e-6):
63
+ super().__init__()
64
+ self.weight = nn.Parameter(torch.ones(dim))
65
+ self.eps = eps
66
+
67
+ def forward(self, x):
68
+ return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps) * self.weight
69
+
70
+
71
+ def build_rope_cache(seq_len: int, head_dim: int, theta: float = 10000.0):
72
+ inv_freq = 1.0 / (theta ** (torch.arange(0, head_dim, 2).float() / head_dim))
73
+ freqs = torch.outer(torch.arange(seq_len, dtype=torch.float32), inv_freq)
74
+ emb = torch.cat([freqs, freqs], dim=-1)
75
+ return emb.cos()[None, None, :, :], emb.sin()[None, None, :, :]
76
+
77
+
78
+ def rotate_half(x):
79
+ x1, x2 = x.chunk(2, dim=-1)
80
+ return torch.cat((-x2, x1), dim=-1)
81
+
82
+
83
+ def apply_rope(q, k, cos, sin):
84
+ T = q.size(2)
85
+ c, s = cos[:, :, :T, :].to(q.dtype), sin[:, :, :T, :].to(q.dtype)
86
+ return (q * c) + (rotate_half(q) * s), (k * c) + (rotate_half(k) * s)
87
+
88
+
89
+ class CausalSelfAttention(nn.Module):
90
+ def __init__(self, d_model: int, n_heads: int, dropout: float):
91
+ super().__init__()
92
+ self.n_heads = n_heads
93
+ self.head_dim = d_model // n_heads
94
+ self.qkv = nn.Linear(d_model, 3 * d_model, bias=False)
95
+ self.out_proj = nn.Linear(d_model, d_model, bias=False)
96
+ self.dropout = dropout
97
+
98
+ def forward(self, x, cos, sin):
99
+ B, T, C = x.shape
100
+ q, k, v = self.qkv(x).view(B, T, 3, self.n_heads, self.head_dim).unbind(dim=2)
101
+ q, k, v = q.transpose(1, 2), k.transpose(1, 2), v.transpose(1, 2)
102
+ q, k = apply_rope(q, k, cos, sin)
103
+ out = F.scaled_dot_product_attention(q, k, v, dropout_p=self.dropout if self.training else 0.0, is_causal=True)
104
+ return self.out_proj(out.transpose(1, 2).contiguous().view(B, T, C))
105
+
106
+
107
+ class SwiGLUMLP(nn.Module):
108
+ def __init__(self, d_model: int, d_ff: int):
109
+ super().__init__()
110
+ self.w_gate = nn.Linear(d_model, d_ff, bias=False)
111
+ self.w_up = nn.Linear(d_model, d_ff, bias=False)
112
+ self.w_down = nn.Linear(d_ff, d_model, bias=False)
113
+
114
+ def forward(self, x):
115
+ return self.w_down(F.silu(self.w_gate(x)) * self.w_up(x))
116
+
117
+
118
+ class TransformerBlock(nn.Module):
119
+ def __init__(self, d_model: int, n_heads: int, d_ff: int, dropout: float):
120
+ super().__init__()
121
+ self.norm1 = RMSNorm(d_model)
122
+ self.attn = CausalSelfAttention(d_model, n_heads, dropout)
123
+ self.norm2 = RMSNorm(d_model)
124
+ self.mlp = SwiGLUMLP(d_model, d_ff)
125
+
126
+ def forward(self, x, cos, sin):
127
+ x = x + self.attn(self.norm1(x), cos, sin)
128
+ return x + self.mlp(self.norm2(x))
129
+
130
+
131
+ class VisionPatchEncoder(nn.Module):
132
+ def __init__(self, d_model: int, n_img_tokens: int):
133
+ super().__init__()
134
+ self.backbone = nn.Sequential(
135
+ nn.Conv2d(3, 64, 3, stride=2, padding=1), nn.GroupNorm(8, 64), nn.GELU(),
136
+ nn.Conv2d(64, 128, 3, stride=2, padding=1), nn.GroupNorm(16, 128), nn.GELU(),
137
+ nn.Conv2d(128, 256, 3, stride=2, padding=1), nn.GroupNorm(32, 256), nn.GELU(),
138
+ nn.Conv2d(256, 256, 3, stride=2, padding=1), nn.GroupNorm(32, 256), nn.GELU(),
139
+ nn.Conv2d(256, 256, 3, stride=1, padding=1), nn.GroupNorm(32, 256), nn.GELU(),
140
+ )
141
+ self.pos_emb = nn.Parameter(torch.randn(1, n_img_tokens, 256) * 0.02)
142
+ self.projector = nn.Sequential(nn.Linear(256, d_model * 2), nn.GELU(), nn.Linear(d_model * 2, d_model))
143
+
144
+ def forward(self, images):
145
+ feat = self.backbone(images).flatten(2).transpose(1, 2) + self.pos_emb
146
+ return self.projector(feat)
147
+
148
+
149
+ class MicroOpsVLM(nn.Module):
150
+ def __init__(self, cfg: dict):
151
+ super().__init__()
152
+ self.cfg = cfg
153
+ vocab_size = cfg.get("vocab_size", 288)
154
+ self.tok_emb = nn.Embedding(vocab_size, cfg["d_model"])
155
+ self.vision = VisionPatchEncoder(cfg["d_model"], cfg["n_img_tokens"])
156
+ self.blocks = nn.ModuleList([
157
+ TransformerBlock(cfg["d_model"], cfg["n_heads"], cfg["d_ff"], cfg.get("dropout", 0.0))
158
+ for _ in range(cfg["n_layers"])
159
+ ])
160
+ self.norm_f = RMSNorm(cfg["d_model"])
161
+ self.lm_head = nn.Linear(cfg["d_model"], vocab_size, bias=False)
162
+ self.lm_head.weight = self.tok_emb.weight
163
+ cos, sin = build_rope_cache(cfg["context_window"], cfg["d_model"] // cfg["n_heads"])
164
+ self.register_buffer("rope_cos", cos, persistent=False)
165
+ self.register_buffer("rope_sin", sin, persistent=False)
166
+
167
+ def forward(self, input_ids, images=None):
168
+ x = self.tok_emb(input_ids)
169
+ if images is not None:
170
+ is_img = (input_ids == 10)
171
+ if is_img.any():
172
+ vis = self.vision(images).to(x.dtype)
173
+ img_pos = (is_img.cumsum(dim=1) - 1).clamp(min=0, max=self.cfg["n_img_tokens"] - 1)
174
+ gathered = torch.gather(vis, 1, img_pos.unsqueeze(-1).expand(-1, -1, x.size(-1)))
175
+ x = torch.where(is_img.unsqueeze(-1), gathered, x)
176
+ for blk in self.blocks:
177
+ x = blk(x, self.rope_cos, self.rope_sin)
178
+ return self.lm_head(self.norm_f(x))
179
+
180
+ @torch.no_grad()
181
+ def generate_turn(self, prompt_ids, image=None, max_new_tokens=220, temperature=0.0):
182
+ self.eval()
183
+ device = next(self.parameters()).device
184
+ tok = ByteAgentTokenizer()
185
+ stop_ids = {tok.end_tool_call_id, tok.end_assistant_id, tok.eos_id}
186
+ idx = torch.tensor([prompt_ids], dtype=torch.long, device=device)
187
+ img_b = image.unsqueeze(0).to(device) if image is not None else None
188
+ out = []
189
+ for _ in range(min(max_new_tokens, self.cfg["context_window"] - idx.size(1))):
190
+ logits = self(idx, images=img_b)[0, -1, :]
191
+ if temperature <= 0.0:
192
+ nxt = int(torch.argmax(logits).item())
193
+ else:
194
+ nxt = int(torch.multinomial(F.softmax(logits / temperature, dim=-1), 1).item())
195
+ out.append(nxt)
196
+ idx = torch.cat([idx, torch.tensor([[nxt]], dtype=torch.long, device=device)], dim=1)
197
+ if nxt in stop_ids:
198
+ break
199
+ return out
200
+
201
+
202
+ def from_pretrained_hf(repo_id: str = "Newone0/MicroOps-VLM", device: str = "cpu"):
203
+ cfg_path = hf_hub_download(repo_id=repo_id, filename="config.json")
204
+ weights_path = hf_hub_download(repo_id=repo_id, filename="model.safetensors")
205
+ with open(cfg_path) as f:
206
+ cfg = json.load(f)
207
+ model = MicroOpsVLM(cfg)
208
+ load_model(model, weights_path)
209
+ return model.to(device).eval(), ByteAgentTokenizer(), cfg