Instructions to use anusoft/OpenThai2.2-OCR-Markdown-20261127-mlx-rocm-pascal with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- MLX
How to use anusoft/OpenThai2.2-OCR-Markdown-20261127-mlx-rocm-pascal with MLX:
# Make sure mlx-vlm is installed # pip install --upgrade mlx-vlm from mlx_vlm import load, generate from mlx_vlm.prompt_utils import apply_chat_template from mlx_vlm.utils import load_config # Load the model model, processor = load("anusoft/OpenThai2.2-OCR-Markdown-20261127-mlx-rocm-pascal") config = load_config("anusoft/OpenThai2.2-OCR-Markdown-20261127-mlx-rocm-pascal") # Prepare input image = ["http://images.cocodataset.org/val2017/000000039769.jpg"] prompt = "Describe this image." # Apply chat template formatted_prompt = apply_chat_template( processor, config, prompt, num_images=1 ) # Generate output output = generate(model, processor, formatted_prompt, image) print(output) - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- LM Studio
- Atomic Chat
File size: 9,814 Bytes
0ec7a7b | 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 | """CUDA-graphed decode step for the 1080 Ti.
Single-token decode is a few dozen tiny kernels. Replaying one graph per token
removes the launch gaps. The KV cache is a fixed bucket so every replay has the
same shapes; positions past the current token are masked out.
"""
from __future__ import annotations
import torch
import torch.nn.functional as F
from bench_loop import penalize
EOS = 2
class GraphedStep:
"""One captured decode step at a fixed KV bucket."""
def __init__(self, model, bucket: int, queries: int = 1, *, attention_kernel=None, kv_dtype=torch.float32):
self.model = model
self.bucket = bucket
self.queries = queries
decoder = model.decoder
self.layers = list(decoder.layers)
self.embed = decoder.embed_tokens
self.embed_norm = decoder.layernorm_embedding
self.final_norm = decoder.layer_norm
self.lm_head = model.lm_head
attention = self.layers[0].self_attn
self.kv_heads = attention.num_kv_heads
self.head_dim = attention.head_dim
self.groups = attention.num_heads // attention.num_kv_heads
self.scale = self.head_dim ** -0.5
self.attention_kernel = attention_kernel
layers = len(self.layers)
self.k = torch.zeros(layers, 1, self.kv_heads, bucket, self.head_dim, device="cuda", dtype=kv_dtype)
self.v = torch.zeros_like(self.k)
self.pos = torch.zeros((), dtype=torch.long, device="cuda")
self.token = torch.zeros(1, queries, dtype=torch.long, device="cuda")
self.idx = None if attention_kernel is not None else torch.arange(bucket, device="cuda")
self.graph = torch.cuda.CUDAGraph()
self.logits = self._capture()
def _attention(self, attention, hidden, keys, values, invalid):
query = attention.q_proj(hidden)
key = attention.k_proj(hidden)
value = attention.v_proj(hidden)
if self.attention_kernel is not None:
return self.attention_kernel(query, key, value, keys, values, self.pos)
slot = self.pos.view(1)
keys.index_copy_(2, slot, key.view(1, 1, self.kv_heads, self.head_dim).transpose(1, 2))
values.index_copy_(2, slot, value.view(1, 1, self.kv_heads, self.head_dim).transpose(1, 2))
grouped = query.view(1, self.kv_heads, self.groups, self.head_dim)
scores = torch.matmul(grouped, keys.transpose(-1, -2)) * self.scale
scores = scores.masked_fill(invalid, float("-inf"))
return torch.matmul(torch.softmax(scores, dim=-1), values).view(1, 1, -1)
def _step(self) -> torch.Tensor:
hidden = self.embed_norm(self.embed(self.token))
invalid = None if self.idx is None else self.idx > self.pos
for index, layer in enumerate(self.layers):
attention = layer.self_attn
normed = layer.self_attn_layer_norm(hidden)
mixed = self._attention(attention, normed, self.k[index], self.v[index], invalid)
hidden = hidden + attention.out_proj(mixed)
hidden = hidden + layer.fc2(F.gelu(layer.fc1(layer.final_layer_norm(hidden))))
return self.lm_head(self.final_norm(hidden))[0, 0]
def _capture(self) -> torch.Tensor:
self.pos.fill_(0)
self.token.fill_(1)
stream = torch.cuda.Stream()
stream.wait_stream(torch.cuda.current_stream())
with torch.cuda.stream(stream), torch.no_grad():
for _ in range(2):
self._step()
torch.cuda.current_stream().wait_stream(stream)
with torch.cuda.graph(self.graph), torch.no_grad():
logits = self._step()
return logits
def load(self, cache, length: int) -> None:
if length >= self.bucket:
raise RuntimeError(f"prefill {length} does not fit bucket {self.bucket}")
for index, layer in enumerate(cache.layers):
self.k[index, :, :, :length].copy_(layer.keys)
self.v[index, :, :, :length].copy_(layer.values)
self.pos.fill_(length)
def inherit(self, step: GraphedStep, length: int) -> None:
self.k[:, :, :, :length].copy_(step.k[:, :, :, :length])
self.v[:, :, :, :length].copy_(step.v[:, :, :, :length])
class GraphedPair(GraphedStep):
"""Captured step that consumes two tokens and returns both logits."""
def __init__(self, model, bucket: int):
self.hidden_out = torch.empty(2, 1024, device="cuda")
super().__init__(model, bucket, queries=2)
def _step(self) -> torch.Tensor:
hidden = self.embed_norm(self.embed(self.token))
later = self.pos + 1
invalid_first = self.idx > self.pos
invalid_second = self.idx > later
for index, layer in enumerate(self.layers):
attention = layer.self_attn
normed = layer.self_attn_layer_norm(hidden)
query = attention.q_proj(normed).view(1, 2, attention.num_heads, self.head_dim).transpose(1, 2)
key = attention.k_proj(normed).view(1, 2, self.kv_heads, self.head_dim).transpose(1, 2)
value = attention.v_proj(normed).view(1, 2, self.kv_heads, self.head_dim).transpose(1, 2)
self.k[index].index_copy_(2, self.pos.view(1), key[:, :, :1])
self.v[index].index_copy_(2, self.pos.view(1), value[:, :, :1])
self.k[index].index_copy_(2, later.view(1), key[:, :, 1:])
self.v[index].index_copy_(2, later.view(1), value[:, :, 1:])
grouped = query.reshape(1, self.kv_heads, self.groups * 2, self.head_dim)
scores = torch.matmul(grouped, self.k[index].transpose(-1, -2)) * self.scale
scores[:, :, 0::2] = scores[:, :, 0::2].masked_fill(invalid_first, float("-inf"))
scores[:, :, 1::2] = scores[:, :, 1::2].masked_fill(invalid_second, float("-inf"))
mixed = torch.matmul(torch.softmax(scores, dim=-1), self.v[index])
mixed = mixed.reshape(1, attention.num_heads, 2, self.head_dim)
hidden = hidden + attention.out_proj(mixed.transpose(1, 2).reshape(1, 2, -1))
hidden = hidden + layer.fc2(F.gelu(layer.fc1(layer.final_layer_norm(hidden))))
final = self.final_norm(hidden)
self.hidden_out.copy_(final[0])
return self.lm_head(final)[0]
class AdaptiveDecoder:
"""Pick the smallest captured bucket and move up when the page outgrows it."""
def __init__(self, model, buckets=(2048, 4096, 8192), *, step_factory=GraphedStep, overflow_bucket=None):
self.model = model
self.step_factory = step_factory
self.steps = [step_factory(model, bucket) for bucket in buckets]
self.overflow_bucket = overflow_bucket
def _fit(self, length: int) -> GraphedStep:
for step in self.steps:
if step.bucket > length:
return step
if self.overflow_bucket is not None and length < self.overflow_bucket:
step = self.step_factory(self.model, self.overflow_bucket)
self.steps.append(step)
self.overflow_bucket = None
return step
raise RuntimeError(f"sequence {length} exceeds the largest bucket")
def load(self, cache, length: int) -> GraphedStep:
step = self._fit(length)
step.load(cache, length)
return step
def promote(self, step: GraphedStep, length: int) -> GraphedStep:
nxt = self._fit(max(length, step.bucket))
nxt.inherit(step, length)
return nxt
@torch.no_grad()
def generate_graphed(step: GraphedStep, model, inputs, limit: int, penalty: float):
seen = torch.empty(9000, dtype=torch.long, device="cuda")
out = model(
input_ids=inputs["input_ids"],
pixel_values=inputs["pixel_values"],
image_sizes=inputs["image_sizes"],
content_sizes=inputs["content_sizes"],
use_cache=True,
)
length = out.past_key_values.get_seq_length()
step.load(out.past_key_values, length)
prompt = inputs["input_ids"][0]
count = int(prompt.numel())
seen[:count].copy_(prompt)
logits = out.logits[0, -1]
produced = 0
while produced < limit:
choice = int(penalize(logits, seen[:count], penalty).argmax())
seen[count] = choice
count += 1
produced += 1
if choice == EOS or produced >= limit:
break
if length + 1 >= step.bucket:
raise RuntimeError("bucket exceeded")
step.token.fill_(choice)
step.pos.fill_(length)
step.graph.replay()
length += 1
logits = step.logits
return seen[:count].view(1, -1)
@torch.no_grad()
def generate_adaptive(decoder: AdaptiveDecoder, model, inputs, limit: int, penalty: float):
"""Greedy tokens using the smallest CUDA graph that still fits."""
prompt = inputs["input_ids"][0]
count = prompt.numel()
seen = torch.empty(count + limit, dtype=torch.long, device=prompt.device)
out = model(
input_ids=inputs["input_ids"],
pixel_values=inputs["pixel_values"],
image_sizes=inputs["image_sizes"],
content_sizes=inputs["content_sizes"],
use_cache=True,
)
length = out.past_key_values.get_seq_length()
step = decoder.load(out.past_key_values, length)
seen[:count].copy_(prompt)
logits = out.logits[0, -1]
produced = 0
while produced < limit:
choice = int(penalize(logits, seen[:count], penalty).argmax())
seen[count] = choice
count += 1
produced += 1
if choice == EOS or produced >= limit:
break
if length >= step.bucket:
step = decoder.promote(step, length)
step.token.fill_(choice)
step.pos.fill_(length)
step.graph.replay()
length += 1
logits = step.logits
return seen[:count].view(1, -1)
|