Spaces:
Running on Zero
Running on Zero
Fix OOM (FP8 experts), streaming chat, hardened agent loop, friendly errors
Browse filesFiles changed (3)
- README.md+41-5
- app.py+444-83
- requirements.txt+2-3
23 unmodified lines242526272829304 unmodified lines3536373839404142434445464748495014 unmodified lines656667686970717273747576777 unmodified lines85868788899023 unmodified lines[huihui-ai/Huihui-Inkling-2-Mini-abliterated](https://huggingface.co/huihui-ai/Huihui-Inkling-2-Mini-abliterated),an abliterated (refusal-removed) build of[thinkingmachines/Inkling-2-Mini](https://huggingface.co/thinkingmachines/Inkling-2-Mini).20B loop-MoE, weights served in NF4 4-bit (~11GB resident), ZeroGPU.**Rules:** placeholder — Garrett supplies Hermes' rules later. Set them inthe `HERMES_SYSTEM_RULES` Space variable/secret; the agent loop prepends4 unmodified linesGPU time draws on the **caller's** ZeroGPU quota — authenticate with aHugging Face token (PRO quota for Garrett's account). Anonymous callersget only a small per-IP allowance.### Gradio API (primary)Named endpoints, callable via `gradio_client` or plain HTTP:- `POST /gradio_api/call/chat` with`{"data": [message, system_prompt, max_new_tokens, reasoning_effort]}`- `POST /gradio_api/call/agent_run` with`{"data": [task, max_steps, max_tokens_per_step, reasoning_effort]}`then read the result from `GET /gradio_api/call/<name>/<event_id>` (SSE).Python:14 unmodified lines`/agent_run` is Hermes as a worker: the server executes tools itself andloops until it reaches a final answer, returning the answer plus a JSONtool trace. Built-in tools: `web_search` (DuckDuckGo, no key), `web_fetch`(read a URL), `current_datetime`.### MCPMCP clients reach this worker through the mcp-hfspace bridge(`evalstate/mcp-hfspace` pattern), which exposes the Space's Gradio APIendpoints as MCP tools:```json{7 unmodified lines}```### Note on the OpenAI-style routes`app.py` also implements OpenAI-shaped handlers (`/v1/models`,23 unmodified lines242526272829303132333435363738394041424344454 unmodified lines505152535455565758596061626364656667686914 unmodified lines848586878889909192939495969798991001017 unmodified lines10911011111211311411511611711811912012112212312412512623 unmodified lines[huihui-ai/Huihui-Inkling-2-Mini-abliterated](https://huggingface.co/huihui-ai/Huihui-Inkling-2-Mini-abliterated),an abliterated (refusal-removed) build of[thinkingmachines/Inkling-2-Mini](https://huggingface.co/thinkingmachines/Inkling-2-Mini).20B loop-MoE (27.9B params total incl. vision/MTP), ZeroGPU.**How it's served (read this before "fixing" the quantization):** thecheckpoint's native format is ModelOpt NVFP4, which transformers cannotload — its NVFP4 quantizer rejects pre-quantized checkpoints and needsBlackwell (sm100+); ZeroGPU is neither. The weights therefore dequantizeto bf16 on load (55.8 GB), and the MoE experts (24.46B params) are raw 3D`nn.Parameter`s, **not** `nn.Linear`s, so bitsandbytes/torchao neverquantize them: a bnb "NF4" build still packs ~51.3 GB onto the 50.87 GBZeroGPU device and OOMs in the worker init on every generation attempt(that was the state until Dec 3, 2026 — the UI showed a bare "Error").`app.py` instead converts every expert matrix to **FP8 e4m3 withper-(row, 128-block) fp32 scales** after load and dequantizes per-expertinside forward: experts 48.9 GB → ~25.2 GB, total GPU footprint ~29 GB,everything else stays full bf16. Weight-level fidelity of the FP8 storeis ~2.6% relative error vs the source values (NF4 would be ~4–6%).**Rules:** placeholder — Garrett supplies Hermes' rules later. Set them inthe `HERMES_SYSTEM_RULES` Space variable/secret; the agent loop prepends4 unmodified linesGPU time draws on the **caller's** ZeroGPU quota — authenticate with aHugging Face token (PRO quota for Garrett's account). Anonymous callersget only a small per-IP allowance. If the quota is exhausted, the UI nowsays so in plain language instead of showing a bare "Error".### Gradio API (primary)Named endpoints (verified against the live `/gradio_api/info` surface,Dec 3, 2026), callable via `gradio_client` or plain HTTP:- `POST /gradio_api/call/chat` with`{"data": [message, system_prompt, max_new_tokens, reasoning_effort]}`— streams; the final SSE `complete` event carries the full reply.- `POST /gradio_api/call/agent_run` with`{"data": [task, max_steps, max_tokens_per_step, reasoning_effort]}`— returns `[final_answer, tool_trace_json]`.then read the result from `GET /gradio_api/call/<name>/<event_id>` (SSE).Python:14 unmodified lines`/agent_run` is Hermes as a worker: the server executes tools itself andloops until it reaches a final answer, returning the answer plus a JSONtool trace. Built-in tools: `web_search` (DuckDuckGo, no key), `web_fetch`(read a URL), `current_datetime`. Hardening: a tool call whose argumentsfail to parse is not executed — the parse error is fed back so the modelcan re-issue it — and a step that exactly repeats the previous step'scalls stops the loop (`stop_reason: "loop_detected"`) instead of burningthe budget.### MCPMCP clients reach this worker through the mcp-hfspace bridge(`evalstate/mcp-hfspace` pattern), which exposes the Space's Gradio APIendpoints (`chat`, `agent_run`, with the parameters listed above) as MCPtools:```json{7 unmodified lines}```### Limits- Cold start ~2.5–3.5 min (19.5 GB download + bf16 load + FP8 conversion+ ZeroGPU tensor packing of ~29 GB).- Each GPU call reserves an estimated duration (30–360 s, scaled byprompt size and requested tokens); a reservation that runs out killsthe call, so very long generations should be chunked — the agent loopalready works this way. Per-call generation is effectively ~2–4ktokens.- The model's native 1M context is addressable in the prompt, but KVcache grows ~200 KB/token; keep prompts sane on the shared slice.### Note on the OpenAI-style routes`app.py` also implements OpenAI-shaped handlers (`/v1/models`,
11 unmodified lines1213141516171819202122232425262728293031323334353637383940414243446 unmodified lines51525354555657585960616263646566676869707172737475767778798011 unmodified lines929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313410 unmodified lines145146147148149150117 unmodified lines26826927027127227327414 unmodified lines2892902912922932942953 unmodified lines2993003013023033043053 unmodified lines30931031131231331431531631711 unmodified lines3293303313323333343353363373383393403413423 unmodified lines34634734834935035135235335435535611 unmodified lines3683693703713723733743754 unmodified lines3803813823833843853866 unmodified lines3933943953963973983994004014024034044054064074084092 unmodified lines41241341441541641741823 unmodified lines44244344444544644744844945045145245345411 unmodified linesimport gradio as gr # noqa: E402import torch # noqa: E402from transformers import AutoTokenizer, Inkling2LoopForConditionalGeneration # noqa: E402MODEL_ID = "huihui-ai/Huihui-Inkling-2-Mini-abliterated"SERVED_NAME = "inkling-2-mini-uncensored"from transformers import BitsAndBytesConfig # noqa: E402# The published weights are FP8-stored (~19.5GB on disk) but upcast to ~53GB# in bf16 — too big for a ZeroGPU "large" slice and too quota-hungry at# xlarge. NF4 4-bit (the pattern proven on this account's other ZeroGPU# space) brings the resident size to ~11GB and keeps calls at 1x quota.bnb = BitsAndBytesConfig(load_in_4bit=True,bnb_4bit_quant_type="nf4",bnb_4bit_use_double_quant=True,bnb_4bit_compute_dtype=torch.bfloat16,)tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)model = Inkling2LoopForConditionalGeneration.from_pretrained(MODEL_ID,quantization_config=bnb,device_map="cuda",attn_implementation="eager", # this arch has no SDPA dispatch in transformerslow_cpu_mem_usage=True,).eval()# Stop conditions: the model's configured EOS plus its explicit# end-of-sampling marker token, when the tokenizer knows it.EOS_IDS = [200006]6 unmodified lines_GEN_LOCK = threading.Lock()THINK_RE = re.compile(r"<\|content_thinking\|>(.*?)<\|end_message\|>", re.DOTALL)TEXT_RE = re.compile(r"<\|content_text\|>(.*?)<\|end_message\|>", re.DOTALL)TOOL_RE = re.compile(r"<\|message_model\|>([A-Za-z0-9_.\-]+)<\|content_invoke_tool_json\|>(\{.*?\})<\|end_message\|>",re.DOTALL,)def parse_completion(raw: str):"""Split a raw Inkling-2 generation into (thinking, text, tool_calls)."""raw = raw.split("<|content_model_end_sampling|>")[0]tool_calls = []for name, payload in TOOL_RE.findall(raw):try:obj = json.loads(payload)args = obj.get("args", {})except Exception:args = {}tool_calls.append({"name": name, "arguments": args})thinking = "\n".join(t.strip() for t in THINK_RE.findall(raw)).strip()text = "\n".join(t.strip() for t in TEXT_RE.findall(raw)).strip()if not text and not tool_calls:# Fallback: strip any leftover special-token markers and use the rest.text = re.sub(r"<\|[a-z0-9_]+\|>", "", raw).strip()return thinking, text, tool_calls11 unmodified linesdef _duration(prompt_text, max_new_tokens, temperature):"""ZeroGPU duration estimate (seconds) for one generation.PRO quota is charged 1x; keep the reservation honest but bounded.Decode for this 20B loop-MoE on the ZeroGPU pool is roughly 15-25 tok/s,so budget generously for long generations."""try:mnt = int(max_new_tokens)except (TypeError, ValueError):mnt = 1024return max(25, min(240, 30 + int(mnt * 0.05)))@spaces.GPU(duration=_duration)def _generate_full(prompt_text, max_new_tokens, temperature):"""Run one generation on the GPU; returns (raw_text, n_generated_tokens)."""inputs = tokenizer([prompt_text], return_tensors="pt", return_token_type_ids=False).to(model.device)prompt_len = inputs["input_ids"].shape[1]gen_kwargs = dict(**inputs,max_new_tokens=int(max_new_tokens),pad_token_id=199999,eos_token_id=EOS_IDS,)if temperature and float(temperature) > 0:gen_kwargs.update(do_sample=True, temperature=float(temperature), top_p=0.95)else:gen_kwargs.update(do_sample=False)with _GEN_LOCK, torch.no_grad():out = model.generate(**gen_kwargs)gen_ids = out[0][prompt_len:]raw = tokenizer.decode(gen_ids, skip_special_tokens=False)return raw, int(gen_ids.shape[0])def run_chat(messages, max_new_tokens=1024, temperature=0.7,reasoning_effort="low", tools=None):"""Full pipeline: render -> generate -> parse. Returns dict."""10 unmodified lines}# --------------------------------------------------------------------------# Built-in tools + agent loop ("works like Hermes": the server can execute# tools itself, feed results back, and iterate to a final answer)117 unmodified linesdef execute_tool(name, arguments):fn = TOOL_EXECUTORS.get(name)if fn is None:return f"Error: unknown tool '{name}'"try:out = fn(**(arguments or {}))except Exception as exc: # tool errors go back to the model, not the user14 unmodified linesdef run_agent(messages, max_steps=6, max_tokens=768, temperature=0.7,reasoning_effort="low"):"""Hermes-style loop: model calls built-in tools, server executes them,results are fed back, repeat until a final text answer or max_steps."""convo = list(messages)system_parts = []if HERMES_RULES:3 unmodified linestrace = []totals = {"prompt_tokens": 0, "completion_tokens": 0}final = Nonefor _step in range(max(1, int(max_steps))):result = run_chat(_normalize_messages(convo),max_new_tokens=max_tokens,3 unmodified lines)totals["prompt_tokens"] += result["prompt_tokens"]totals["completion_tokens"] += result["completion_tokens"]if not result["tool_calls"]:final = resultbreakassistant_msg = {"role": "assistant", "content": result["text"] or None}calls = []for tc in result["tool_calls"]:11 unmodified linesassistant_msg["tool_calls"] = callsconvo.append(assistant_msg)for call, tc in zip(calls, result["tool_calls"]):output = execute_tool(tc["name"], tc["arguments"])trace.append({"tool": tc["name"],"arguments": tc["arguments"],"result_preview": output[:500],})convo.append({"role": "tool",3 unmodified lines})if final is None:final = {"text": "(agent stopped: max_steps reached)", "thinking": "","tool_calls": [], "prompt_tokens": 0, "completion_tokens": 0}stop_reason = "max_steps"else:stop_reason = "final_answer"return {"final_text": final["text"],"steps": trace,11 unmodified lines# Gradio UI# --------------------------------------------------------------------------def chat(message, history, system_prompt, max_new_tokens, reasoning_effort):"""Chat with Inkling-2-Mini (abliterated / uncensored).Args:message: The user's message.4 unmodified lineslonger internal thinking before the answer.Returns:The assistant's reply."""messages = []if system_prompt and system_prompt.strip():6 unmodified lines)messages.append({"role": m.get("role", "user"), "content": content})messages.append({"role": "user", "content": message})result = run_chat(messages,max_new_tokens=int(max_new_tokens),temperature=0.7,reasoning_effort=reasoning_effort or "low",)if result["tool_calls"]:return "Tool call(s):\n```json\n" + json.dumps(result["tool_calls"], indent=2) + "\n```"return result["text"] or "(empty response)"DESCRIPTION = """2 unmodified linesGarrett's autonomous worker, built on[huihui-ai/Huihui-Inkling-2-Mini-abliterated](https://huggingface.co/huihui-ai/Huihui-Inkling-2-Mini-abliterated)(abliterated build of [thinkingmachines/Inkling-2-Mini](https://huggingface.co/thinkingmachines/Inkling-2-Mini))· 20B loop-MoE · bf16 · ZeroGPUAccess: Gradio API endpoints `/chat` and `/agent_run` (gradio_client orHTTP queue-call), and MCP via the mcp-hfspace bridge (see the Space README).23 unmodified linesReturns:The final answer, and a JSON trace of the tools it used."""agent = run_agent([{"role": "user", "content": task}],max_steps=int(max_steps),max_tokens=int(max_tokens),temperature=0.7,reasoning_effort=reasoning_effort or "low",)trace = json.dumps({"steps": agent["steps"],11 unmodified lines121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511526 unmodified lines15916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730811 unmodified lines32032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239310 unmodified lines404405406407408409410411412413414415416417418419420421422423424425426427428429430431117 unmodified lines54955055155255355455555655755814 unmodified lines5735745755765775785795805815825835843 unmodified lines5885895905915925935945955965975983 unmodified lines60260360460560660760860961061161261361461561661761861962062162262362462562662762862911 unmodified lines6416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716723 unmodified lines67667767867968068168268368468568668768811 unmodified lines7007017027037047057067077087097107117127137147157167177184 unmodified lines7237247257267277287296 unmodified lines7367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657662 unmodified lines76977077177277377477523 unmodified lines79980080180280380480580680780880981081181281381481511 unmodified linesimport gradio as gr # noqa: E402import torch # noqa: E402import torch.nn.functional as F # noqa: E402from transformers import AutoTokenizer, Inkling2LoopForConditionalGeneration # noqa: E402from transformers.models.inkling2_loop.modeling_inkling2_loop import ( # noqa: E402Inkling2LoopExperts,)MODEL_ID = "huihui-ai/Huihui-Inkling-2-Mini-abliterated"SERVED_NAME = "inkling-2-mini-uncensored"# ---------------------------------------------------------------------------# FP8 expert storage (the memory fix)## The checkpoint's native quantization is ModelOpt NVFP4, which# transformers cannot load (its NVFP4 quantizer rejects pre-quantized# checkpoints and requires Blackwell sm100+; ZeroGPU is neither), so the# weights are dequantized to bf16 on load: 55.8 GB total. The MoE experts# are 24.46B of those params held as raw 3D nn.Parameters — NOT nn.Linear# modules — so bitsandbytes/torchao quantizers never touch them, and the# earlier "NF4" build still packed ~51.3 GB onto a 50.87 GB device and# OOM'd in the ZeroGPU worker init on every real generation attempt.## Fix: after load, store every expert matrix as FP8 e4m3 with per-(row,# 128-block) fp32 scales and dequantize per-expert inside forward (the# stock forward already loops over hit experts one at a time). Experts go# 48.9 GB -> ~25.2 GB; total GPU footprint ~29 GB. Everything else stays# full bf16 (better fidelity than the old NF4-on-dense path). Measured on# the real module class offline: weight-level rel. error ~2.6% (NF4 is# ~4-6%); block size barely matters (e4m3 mantissa dominates), so 128.# ---------------------------------------------------------------------------FP8_BLOCK = 128_FP8_MAX = 448.0 # float8_e4m3fn maxdef _fp8_quantize_2d(w, block=FP8_BLOCK):"""[out, in] -> (q float8_e4m3fn [out, in], scale fp32 [out, in/block])."""out, inn = w.shapev = w.float().view(out, inn // block, block)scale = (v.abs().amax(dim=-1) / _FP8_MAX).clamp_min(1e-12)q = (v / scale.unsqueeze(-1)).to(torch.float8_e4m3fn)return q.view(out, inn), scaledef _fp8_dequantize_2d(q, scale, block=FP8_BLOCK):"""Inverse of _fp8_quantize_2d; returns bf16 [out, in]."""out, inn = q.shapev = q.float().view(out, inn // block, block)v = v * scale.unsqueeze(-1)return v.view(out, inn).to(torch.bfloat16)def _fp8_experts_forward(self, hidden_states, top_k_index, top_k_weights):"""Drop-in replacement for Inkling2LoopExperts.forward reading the FP8buffers instead of the bf16 Parameters. Mirrors the stock forwardexactly, except each hit expert's two matrices are dequantized justbefore its F.linear calls."""final_hidden_states = torch.zeros_like(hidden_states, dtype=torch.float32)with torch.no_grad():expert_mask = F.one_hot(top_k_index, num_classes=self.num_experts + 1).permute(2, 1, 0)expert_hit = torch.greater(expert_mask.sum(dim=(-1, -2)), 0).nonzero()for expert_idx in expert_hit:expert_idx = expert_idx[0]if expert_idx == self.num_experts:continuetop_k_pos, token_idx = torch.where(expert_mask[expert_idx])current_state = hidden_states[token_idx]gate_up_w = _fp8_dequantize_2d(self.gate_up_proj_q[expert_idx], self.gate_up_proj_scale[expert_idx])down_w = _fp8_dequantize_2d(self.down_proj_q[expert_idx], self.down_proj_scale[expert_idx])current_hidden_states = self._apply_gate(F.linear(current_state, gate_up_w))current_hidden_states = F.linear(current_hidden_states, down_w)current_hidden_states = current_hidden_states * top_k_weights[token_idx, top_k_pos, None]final_hidden_states.index_add_(0, token_idx, current_hidden_states.to(final_hidden_states.dtype))return final_hidden_states.to(hidden_states.dtype)def _convert_experts_module_to_fp8_(module):"""Convert one Inkling2LoopExperts module's bf16 Parameters to FP8buffers, in place. Returns bytes saved."""saved = 0for name in ("gate_up_proj", "down_proj"):p = module._parameters.pop(name)w = p.data # [E, O, I]E, O, I = w.shapeq2, s2 = _fp8_quantize_2d(w.reshape(E * O, I))module.register_buffer(name + "_q", q2.view(E, O, I))module.register_buffer(name + "_scale", s2.view(E, O, I // FP8_BLOCK))saved += w.numel() * 2 - (q2.numel() + s2.numel() * 4)del p, w, q2, s2module._hermes_fp8 = Truereturn saveddef _install_fp8_experts_patch():"""Route Inkling2LoopExperts.forward through the FP8 path forconverted modules; unconverted modules keep the stock forward."""if getattr(Inkling2LoopExperts, "_hermes_fp8_patched", False):returnstock_forward = Inkling2LoopExperts.forwarddef dispatched_forward(self, hidden_states, top_k_index, top_k_weights):if getattr(self, "_hermes_fp8", False):return _fp8_experts_forward(self, hidden_states, top_k_index, top_k_weights)return stock_forward(self, hidden_states, top_k_index, top_k_weights)Inkling2LoopExperts.forward = dispatched_forwardInkling2LoopExperts._hermes_fp8_patched = Truetokenizer = AutoTokenizer.from_pretrained(MODEL_ID)model = Inkling2LoopForConditionalGeneration.from_pretrained(MODEL_ID,device_map="cuda",attn_implementation="eager", # this arch has no SDPA dispatch in transformerslow_cpu_mem_usage=True,).eval()_install_fp8_experts_patch()_saved_bytes = 0_n_expert_modules = 0for _m in model.modules():if isinstance(_m, Inkling2LoopExperts):_saved_bytes += _convert_experts_module_to_fp8_(_m)_n_expert_modules += 1print(f"[hermes] FP8 experts: {_n_expert_modules} modules converted, "f"{_saved_bytes / 1e9:.2f} GB saved",flush=True,)# Stop conditions: the model's configured EOS plus its explicit# end-of-sampling marker token, when the tokenizer knows it.EOS_IDS = [200006]6 unmodified lines_GEN_LOCK = threading.Lock()# ---------------------------------------------------------------------------# Completion parsing (json/re only — kept dependency-light on purpose)## Wire format (from the model's own chat template): thinking arrives as# <|content_thinking|>...<|end_message|>, text as# <|content_text|>...<|end_message|>, and each tool call as# <|message_model|>{name}<|content_invoke_tool_json|>{"name":...,"args":{...}}<|end_message|># ---------------------------------------------------------------------------THINK_RE = re.compile(r"<\|content_thinking\|>(.*?)<\|end_message\|>", re.DOTALL)TEXT_RE = re.compile(r"<\|content_text\|>(.*?)<\|end_message\|>", re.DOTALL)TOOL_OPEN_RE = re.compile(r"<\|message_model\|>([A-Za-z0-9_.\-]+)<\|content_invoke_tool_json\|>")def _extract_json_object(s, start):"""Brace-matching scan from s[start] == '{'. Returns (obj_str, end_idx),or (None, start) if the object is unbalanced (truncated generation).String- and escape-aware."""depth = 0in_str = Falseesc = Falsefor i in range(start, len(s)):c = s[i]if in_str:if esc:esc = Falseelif c == "\\":esc = Trueelif c == '"':in_str = Falseelse:if c == '"':in_str = Trueelif c == "{":depth += 1elif c == "}":depth -= 1if depth == 0:return s[start : i + 1], i + 1return None, startdef _repair_json(s):"""Best-effort repairs for malformed tool JSON: drop trailing commas andclose unbalanced brackets/braces (string-aware)."""s = re.sub(r",\s*([}\]])", r"\1", s)curly = square = 0in_str = Falseesc = Falsefor c in s:if in_str:if esc:esc = Falseelif c == "\\":esc = Trueelif c == '"':in_str = Falseelse:if c == '"':in_str = Trueelif c == "{":curly += 1elif c == "}":curly -= 1elif c == "[":square += 1elif c == "]":square -= 1if in_str:s += '"'return s + "]" * max(0, square) + "}" * max(0, curly)def _parse_tool_payload(payload):"""Parse one tool-call payload. Returns (args_dict, error_or_None).Accepts the template's {"name": ..., "args": {...}} wrapper and a bareargs object. On failure, attempts one repair pass; if still broken,returns the error so the caller can feed it back to the model insteadof executing a bogus call."""try:obj = json.loads(payload)except Exception:try:obj = json.loads(_repair_json(payload))except Exception as exc:return {}, f"unparseable tool arguments ({exc})"if not isinstance(obj, dict):return {}, "tool arguments are not a JSON object"if isinstance(obj.get("args"), dict):return obj["args"], Noneif set(obj) <= {"name", "args"}:return {}, Nonereturn obj, Nonedef parse_completion(raw: str):"""Split a raw Inkling-2 generation into (thinking, text, tool_calls).Each tool call is {"name", "arguments", "parse_error", "raw_arguments"};parse_error is None for clean calls. Truncated or malformed calls aresurfaced with an error instead of being silently dropped or executedwith empty arguments."""raw = raw.split("<|content_model_end_sampling|>")[0]tool_calls = []spans = []for m in TOOL_OPEN_RE.finditer(raw):name = m.group(1)jstart = raw.find("{", m.end())if jstart == -1:tool_calls.append({"name": name,"arguments": {},"parse_error": "truncated tool call (no arguments emitted)","raw_arguments": None,})spans.append((m.start(), len(raw)))continuepayload, jend = _extract_json_object(raw, jstart)if payload is None: # unbalanced -> generation was cut off mid-JSONpayload = raw[jstart:]jend = len(raw)args, err = _parse_tool_payload(payload)tool_calls.append({"name": name,"arguments": args,"parse_error": err,"raw_arguments": payload if err else None,})spans.append((m.start(), jend))thinking = "\n".join(t.strip() for t in THINK_RE.findall(raw)).strip()text = "\n".join(t.strip() for t in TEXT_RE.findall(raw)).strip()if not text and not any(tc["parse_error"] is None for tc in tool_calls):# Fallback (also when every tool call is broken): remove any# tool-invoke blocks, strip leftover special-token markers, and# use the rest as the text.cleaned = rawfor a, b in sorted(spans, reverse=True):cleaned = cleaned[:a] + cleaned[b:]text = re.sub(r"<\|[a-z0-9_]+\|>", "", cleaned).strip()return thinking, text, tool_calls11 unmodified linesdef _duration(prompt_text, max_new_tokens, temperature):"""ZeroGPU duration estimate (seconds) for one generation.Decode for this 20B loop-MoE on the ZeroGPU pool is roughly 15-25tok/s; the reservation scales with requested tokens plus a smallprefill term for the prompt. A too-small estimate gets the callkilled mid-generation, so the bounds err generous: floor 30s (thefixed cost of moving tensors to the GPU), cap 360s."""try:mnt = int(max_new_tokens)except (TypeError, ValueError):mnt = 1024prompt_tokens = len(prompt_text) / 3.5 if isinstance(prompt_text, str) else 0est = 25 + prompt_tokens * 0.01 + mnt * 0.055return max(30, min(360, int(est)))def _gen_kwargs(inputs, max_new_tokens, temperature, streamer=None):kwargs = dict(**inputs,max_new_tokens=int(max_new_tokens),pad_token_id=199999,eos_token_id=EOS_IDS,)if streamer is not None:kwargs["streamer"] = streamerif temperature and float(temperature) > 0:kwargs.update(do_sample=True, temperature=float(temperature), top_p=0.95)else:kwargs.update(do_sample=False)return kwargs@spaces.GPU(duration=_duration)def _generate_full(prompt_text, max_new_tokens, temperature):"""Run one generation on the GPU; returns (raw_text, n_generated_tokens)."""inputs = tokenizer([prompt_text], return_tensors="pt", return_token_type_ids=False).to(model.device)prompt_len = inputs["input_ids"].shape[1]with _GEN_LOCK, torch.no_grad():out = model.generate(**_gen_kwargs(inputs, max_new_tokens, temperature))gen_ids = out[0][prompt_len:]raw = tokenizer.decode(gen_ids, skip_special_tokens=False)return raw, int(gen_ids.shape[0])@spaces.GPU(duration=_duration)def _generate_stream(prompt_text, max_new_tokens, temperature):"""Stream one generation token-chunk by token-chunk (ZeroGPU keeps theGPU attached while the generator is consumed). Yields decoded piecesincluding special-token markers; callers re-parse incrementally."""from transformers import TextIteratorStreamerinputs = tokenizer([prompt_text], return_tensors="pt", return_token_type_ids=False).to(model.device)streamer = TextIteratorStreamer(tokenizer, skip_prompt=True, skip_special_tokens=False)kwargs = _gen_kwargs(inputs, max_new_tokens, temperature, streamer=streamer)with _GEN_LOCK:thread = threading.Thread(target=model.generate, kwargs=kwargs)thread.start()try:for chunk in streamer:yield chunkfinally:thread.join()def run_chat(messages, max_new_tokens=1024, temperature=0.7,reasoning_effort="low", tools=None):"""Full pipeline: render -> generate -> parse. Returns dict."""10 unmodified lines}def _friendly_error(exc):"""Translate a generation failure into a human-readable message.Gradio renders bare 'Error' for untranslated exceptions; the UI layerre-raises these as gr.Error so the user sees the actual reason."""msg = str(exc) or exc.__class__.__name__low = msg.lower()if "quota" in low:return ("ZeroGPU quota exhausted. This Space runs on the caller's ""ZeroGPU quota, which refills on a rolling window — wait for ""the reset and try again, or call the API with a Hugging Face ""token that has quota available. (Details: " + msg[:200] + ")")if "out of memory" in low or "nvml" in low or "pack_to_cuda" in low:return ("The model failed to load onto the GPU (out of memory). This ""is a serving-side fault, not your message — it has been ""logged. If it persists, the Space needs attention.")return "Generation failed: " + msg[:300]# --------------------------------------------------------------------------# Built-in tools + agent loop ("works like Hermes": the server can execute# tools itself, feed results back, and iterate to a final answer)117 unmodified linesdef execute_tool(name, arguments):fn = TOOL_EXECUTORS.get(name)if fn is None:return (f"Error: unknown tool '{name}'. Available tools: "+ ", ".join(sorted(TOOL_EXECUTORS)))try:out = fn(**(arguments or {}))except Exception as exc: # tool errors go back to the model, not the user14 unmodified linesdef run_agent(messages, max_steps=6, max_tokens=768, temperature=0.7,reasoning_effort="low"):"""Hermes-style loop: model calls built-in tools, server executes them,results are fed back, repeat until a final text answer or max_steps.Hardening: a tool call whose arguments failed to parse is NOT executed— the parse error is fed back so the model can re-issue it. A step thatrepeats the previous step's exact tool calls is detected; repeatingagain stops the loop instead of burning the whole budget."""convo = list(messages)system_parts = []if HERMES_RULES:3 unmodified linestrace = []totals = {"prompt_tokens": 0, "completion_tokens": 0}final = Nonestop_reason = "max_steps"last_text = ""prev_signature = Nonerepeats = 0for step_no in range(1, max(1, int(max_steps)) + 1):result = run_chat(_normalize_messages(convo),max_new_tokens=max_tokens,3 unmodified lines)totals["prompt_tokens"] += result["prompt_tokens"]totals["completion_tokens"] += result["completion_tokens"]if result["text"]:last_text = result["text"]if not result["tool_calls"]:final = resultstop_reason = "final_answer"breaksignature = json.dumps([{"name": tc["name"], "arguments": tc["arguments"]}for tc in result["tool_calls"]],sort_keys=True,default=str,)if signature == prev_signature:repeats += 1if repeats >= 2:stop_reason = "loop_detected"breakelse:repeats = 0prev_signature = signatureassistant_msg = {"role": "assistant", "content": result["text"] or None}calls = []for tc in result["tool_calls"]:11 unmodified linesassistant_msg["tool_calls"] = callsconvo.append(assistant_msg)for call, tc in zip(calls, result["tool_calls"]):if tc.get("parse_error"):output = (f"Error: your {tc['name']} tool call was not executed "f"because its arguments could not be parsed: "f"{tc['parse_error']}. Re-issue the call with valid "f"JSON arguments.")trace.append({"step": step_no,"tool": tc["name"],"arguments": tc["arguments"],"parse_error": tc["parse_error"],"result_preview": output[:500],})else:output = execute_tool(tc["name"], tc["arguments"])trace.append({"step": step_no,"tool": tc["name"],"arguments": tc["arguments"],"result_preview": output[:500],})convo.append({"role": "tool",3 unmodified lines})if final is None:final = {"text": last_text or "(agent stopped: max_steps reached)","thinking": "","tool_calls": [],"prompt_tokens": 0,"completion_tokens": 0,}return {"final_text": final["text"],"steps": trace,11 unmodified lines# Gradio UI# --------------------------------------------------------------------------def _format_tool_calls(tool_calls):return "Tool call(s):\n```json\n" + json.dumps([{"name": tc["name"], "arguments": tc["arguments"]}for tc in tool_calls],indent=2,) + "\n```"def chat(message, history, system_prompt, max_new_tokens, reasoning_effort):"""Chat with Inkling-2-Mini (abliterated / uncensored). Streams thereply as it is generated.Args:message: The user's message.4 unmodified lineslonger internal thinking before the answer.Returns:The assistant's reply (streamed)."""messages = []if system_prompt and system_prompt.strip():6 unmodified lines)messages.append({"role": m.get("role", "user"), "content": content})messages.append({"role": "user", "content": message})prompt_text = render_prompt(messages, None, reasoning_effort or "low")raw_acc = ""last_shown = Nonetry:for chunk in _generate_stream(prompt_text, int(max_new_tokens), 0.7):raw_acc += chunk_, text, tool_calls = parse_completion(raw_acc)if tool_calls:shown = _format_tool_calls(tool_calls)elif text:shown = textelse:shown = "…"if shown != last_shown:last_shown = shownyield shownexcept Exception as exc:raise gr.Error(_friendly_error(exc)) from exc_, text, tool_calls = parse_completion(raw_acc)if tool_calls:yield _format_tool_calls(tool_calls)else:yield text or "(empty response)"DESCRIPTION = """2 unmodified linesGarrett's autonomous worker, built on[huihui-ai/Huihui-Inkling-2-Mini-abliterated](https://huggingface.co/huihui-ai/Huihui-Inkling-2-Mini-abliterated)(abliterated build of [thinkingmachines/Inkling-2-Mini](https://huggingface.co/thinkingmachines/Inkling-2-Mini))· 20B loop-MoE · experts in FP8, rest bf16 · ZeroGPUAccess: Gradio API endpoints `/chat` and `/agent_run` (gradio_client orHTTP queue-call), and MCP via the mcp-hfspace bridge (see the Space README).23 unmodified linesReturns:The final answer, and a JSON trace of the tools it used."""try:agent = run_agent([{"role": "user", "content": task}],max_steps=int(max_steps),max_tokens=int(max_tokens),temperature=0.7,reasoning_effort=reasoning_effort or "low",)except Exception as exc:msg = _friendly_error(exc)return msg, json.dumps({"error": msg}, indent=2)trace = json.dumps({"steps": agent["steps"],
1234transformers==5.25.1acceleratebitsandbytes>=0.46.1uvicorn123transformers==5.25.1accelerate==1.16.0requests
README.md+41-5
app.py+444-83
requirements.txt+2-3