Text Generation
Transformers
Safetensors
qwen3_5_text
decision-model
system-one
qwen3_5
custom-inference
text-only
Instructions to use Patrick-18/Dexy-Decision-9B with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use Patrick-18/Dexy-Decision-9B with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-generation", model="Patrick-18/Dexy-Decision-9B")# pip install -U transformers accelerate # Load model directly from transformers import AutoTokenizer, AutoModelForCausalLM tokenizer = AutoTokenizer.from_pretrained("Patrick-18/Dexy-Decision-9B") model = AutoModelForCausalLM.from_pretrained("Patrick-18/Dexy-Decision-9B", device_map="auto") - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- vLLM
How to use Patrick-18/Dexy-Decision-9B with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "Patrick-18/Dexy-Decision-9B" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "Patrick-18/Dexy-Decision-9B", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }'Use Docker
docker model run hf.co/Patrick-18/Dexy-Decision-9B
- SGLang
How to use Patrick-18/Dexy-Decision-9B with SGLang:
Install from pip and serve model
# Install SGLang from pip: pip install sglang # Start the SGLang server: python3 -m sglang.launch_server \ --model-path "Patrick-18/Dexy-Decision-9B" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "Patrick-18/Dexy-Decision-9B", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }'Use Docker images
docker run --gpus all \ --shm-size 32g \ -p 30000:30000 \ -v ~/.cache/huggingface:/root/.cache/huggingface \ --env "HF_TOKEN=<secret>" \ --ipc=host \ lmsysorg/sglang:latest \ python3 -m sglang.launch_server \ --model-path "Patrick-18/Dexy-Decision-9B" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "Patrick-18/Dexy-Decision-9B", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }' - Docker Model Runner
How to use Patrick-18/Dexy-Decision-9B with Docker Model Runner:
docker model run hf.co/Patrick-18/Dexy-Decision-9B
Download decision_runtime.py from Patrick-18/Dexy-Decision-9B: direct link, hf CLI and curl.
- Browser
- Download file 11.2 kB
-
https://huggingface.co/Patrick-18/Dexy-Decision-9B/resolve/main/decision_runtime.py
- Command line
-
hf download hf://Patrick-18/Dexy-Decision-9B/decision_runtime.py
-
curl -L -o decision_runtime.py https://huggingface.co/Patrick-18/Dexy-Decision-9B/resolve/main/decision_runtime.py
11.2 kB
| """System One inference for the Qwen3.5 decision model.""" | |
| import hashlib | |
| import json | |
| import math | |
| import time | |
| import uuid | |
| from pathlib import Path | |
| def validate_decision_config(decision, tokenizer=None): | |
| ids, bias = decision['verbalizer_ids'], decision['bias'] | |
| if len(ids) != len(bias) or len(set(ids)) != len(ids) or not all(math.isfinite(x) for x in bias): | |
| raise ValueError('Invalid decision token IDs or FP32 bias') | |
| slots = [] | |
| for kind in ('noul', 'score', 'choice'): | |
| lo, hi = decision['ranges'][kind] | |
| labels = decision['verbalizers'][kind] | |
| if not 0 <= lo < hi <= len(ids) or not 2 <= hi - lo <= 256 or len(labels) != hi - lo: | |
| raise ValueError(f'Invalid {kind} capacity or labels') | |
| if kind == 'noul' and hi - lo != 2: | |
| raise ValueError('noul requires two slots') | |
| temperature = decision['temperatures'][kind] | |
| if not math.isfinite(temperature) or temperature <= 0: | |
| raise ValueError(f'Invalid {kind} temperature') | |
| if tokenizer is not None and [tokenizer.encode(x, add_special_tokens=False) | |
| for x in labels] != [[i] for i in ids[lo:hi]]: | |
| raise ValueError(f'Saved {kind} token mapping does not match tokenizer') | |
| slots.extend(range(lo, hi)) | |
| if sorted(slots) != list(range(len(ids))): | |
| raise ValueError('Decision ranges must cover the head without overlap') | |
| def render_prompt(state, kind, question, options, decision): | |
| """Render the decision prompt using the saved label mapping.""" | |
| state = state if isinstance(state, str) else json.dumps(state, ensure_ascii=False) | |
| labels = decision['verbalizers'][kind] | |
| if not 2 <= len(options) <= len(labels): | |
| raise ValueError(f'{kind} requires 2..{len(labels)} options') | |
| if kind == 'choice': | |
| lines = [f'{labels[i]}) {opt}' for i, opt in enumerate(options)] | |
| elif kind == 'score': | |
| lines = [str(opt) if labels[i] == str(opt) else f'{labels[i]}) {i}: {opt}' for i, opt in enumerate(options)] | |
| elif kind == 'noul': | |
| lines = [str(opt) for opt in options] | |
| else: | |
| raise ValueError(f'unknown question type: {kind}') | |
| return (f'[kind] {kind}\n[state] {state}\n[question] {question}\n[options]\n' + '\n'.join(lines) + '\n[decision]:') | |
| def prepare_question(state, question, decision): | |
| """Convert a System One question to a prompt and ordered output keys.""" | |
| kind = question['type'] | |
| text = question.get('instructions', '') | |
| criteria = question.get('criteria') | |
| if kind == 'choice': | |
| keys = list(criteria) | |
| options = [ | |
| str(key) + (': ' + str(criteria[key]) if isinstance(criteria, dict) and criteria[key] else '') | |
| for key in keys | |
| ] | |
| elif kind == 'score': | |
| keys = options = [str(i) for i in range(len(criteria))] | |
| text += '\n评分等级 / Rating levels:\n' + '\n'.join(f'{i}: {v}' for i, v in enumerate(criteria)) | |
| elif kind == 'noul': | |
| keys = options = ['false', 'true'] | |
| if criteria: | |
| text += '\n判断标准:\n' + '\n'.join(f'{key}: {criteria[key]}' for key in keys if key in criteria) | |
| else: | |
| raise ValueError(f'unsupported type: {kind}') | |
| return render_prompt(state, kind, text, options, decision), kind, keys | |
| def validate_request(request): | |
| """Validate the text System One request shared by local and HTTP inference.""" | |
| if not isinstance(request, dict) or 'state' not in request: | |
| raise ValueError('A request requires state and questions') | |
| def media(value): | |
| if isinstance(value, dict): | |
| return set(value) in ({'image'}, {'video'}, {'audio'}) or any(media(v) for v in value.values()) | |
| return isinstance(value, list) and any(media(v) for v in value) | |
| if media(request['state']) or request.get('images'): | |
| raise ValueError('This model supports text only') | |
| questions = request.get('questions') | |
| if not isinstance(questions, dict) or not questions: | |
| raise ValueError('questions must be a nonempty object') | |
| if not isinstance(request.get('include_diagnostics', False), bool): | |
| raise ValueError('include_diagnostics must be a boolean') | |
| for qid, q in questions.items(): | |
| if not isinstance(qid, str) or not qid or not isinstance(q, dict): | |
| raise ValueError('Each question needs a nonempty string ID and an object value') | |
| if not isinstance(q.get('instructions', ''), str): | |
| raise ValueError('instructions must be a string') | |
| kind, criteria = q.get('type'), q.get('criteria') | |
| if kind == 'choice': | |
| if not isinstance(criteria, (dict, list)) or not 2 <= len(criteria) <= 256: | |
| raise ValueError('choice requires 2..256 candidates in a map or list') | |
| keys = list(criteria) | |
| if any(not isinstance(k, str) or not k for k in keys) or len(set(keys)) != len(keys): | |
| raise ValueError('choice candidate names must be unique nonempty strings') | |
| elif kind == 'score': | |
| if not isinstance(criteria, list) or not 2 <= len(criteria) <= 256: | |
| raise ValueError('score requires an ordered list of 2..256 levels') | |
| elif kind == 'noul': | |
| if criteria is not None and not isinstance(criteria, dict): | |
| raise ValueError('noul criteria must be null or a map') | |
| else: | |
| raise ValueError(f'Unsupported question type: {kind}') | |
| def format_answer(kind, keys, probabilities, criteria=None): | |
| """System One answer; score is the expected zero-based level.""" | |
| probs = [float(p) for p in probabilities] | |
| if len(keys) != len(probs) or not probs or any(not math.isfinite(p) or not 0 <= p <= 1 for p in probs): | |
| raise ValueError('Invalid decision probability distribution') | |
| if abs(sum(probs) - 1) > 1e-5: | |
| raise ValueError('Decision probabilities must sum to one') | |
| answer = {'type': kind, 'probabilities': dict(zip(keys, probs)), 'confidence': max(probs)} | |
| if kind == 'noul': | |
| answer['noul'] = probs[1] | |
| elif kind == 'choice': | |
| answer['choice'] = keys[max(range(len(probs)), key=probs.__getitem__)] | |
| elif kind == 'score': | |
| answer['score'] = sum(i * p for i, p in enumerate(probs)) | |
| answer['legend'] = dict(zip(keys, criteria)) | |
| else: | |
| raise ValueError(f'Unsupported question type: {kind}') | |
| return answer | |
| class DecisionModel: | |
| """Accepts any Transformers-loadable quantized replacement backbone directory. | |
| decision_config.json may stay in the BF16 release, independent of --model. | |
| """ | |
| def __init__(self, | |
| model_dir, | |
| device='cuda:0', | |
| decision_config=None, | |
| dtype='bfloat16', | |
| attn_impl='sdpa', | |
| load_in_4bit=False, | |
| load_in_8bit=False, | |
| max_model_len=65536): | |
| import torch | |
| from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig | |
| self.torch = torch | |
| self.model_dir = Path(model_dir) | |
| config_path = Path(decision_config) if decision_config else self.model_dir / 'decision_config.json' | |
| self.decision = json.loads(config_path.read_text()) | |
| self.tokenizer = AutoTokenizer.from_pretrained(self.model_dir, local_files_only=True) | |
| validate_decision_config(self.decision, self.tokenizer) | |
| if load_in_4bit and load_in_8bit: | |
| raise ValueError('choose only one bitsandbytes load mode') | |
| kwargs = { | |
| 'device_map': device, | |
| 'local_files_only': True, | |
| 'attn_implementation': attn_impl, | |
| 'dtype': getattr(torch, dtype) | |
| } | |
| if load_in_4bit or load_in_8bit: | |
| kwargs['quantization_config'] = BitsAndBytesConfig( | |
| load_in_4bit=load_in_4bit, | |
| load_in_8bit=load_in_8bit, | |
| bnb_4bit_compute_dtype=torch.bfloat16, | |
| bnb_4bit_quant_type='nf4', | |
| bnb_4bit_use_double_quant=True, | |
| llm_int8_skip_modules=['lm_head']) | |
| self.model = AutoModelForCausalLM.from_pretrained(self.model_dir, **kwargs).eval() | |
| self.model.config.use_cache = False | |
| self.max_model_len = min(int(max_model_len), self.model.config.max_position_embeddings) | |
| if self.max_model_len < 2: | |
| raise ValueError("max_model_len must be at least 2") | |
| self.device = self.model.get_input_embeddings().weight.device | |
| self.bias = torch.tensor(self.decision['bias'], dtype=torch.float32, device=self.device) | |
| self.ids = torch.tensor(self.decision['verbalizer_ids'], dtype=torch.long, device=self.device) | |
| def predict_prompt(self, text, kind, count): | |
| torch = self.torch | |
| lo, hi = self.decision['ranges'][kind] | |
| if not 2 <= count <= hi - lo: | |
| raise ValueError(f'unsupported {kind} option count: {count}') | |
| ids = self.tokenizer.encode(text, add_special_tokens=False) | |
| maximum = self.max_model_len | |
| if not ids or len(ids) + 1 > maximum: | |
| raise ValueError(f'invalid token length: {len(ids)}') | |
| inputs = torch.tensor([ids], device=self.device, dtype=torch.long) | |
| with torch.inference_mode(): | |
| # One prompt at a time, no padding; only project its final hidden state to vocabulary. | |
| output = self.model( | |
| input_ids=inputs, | |
| attention_mask=torch.ones_like(inputs), | |
| use_cache=False, | |
| logits_to_keep=1, | |
| return_dict=True) | |
| logits = output.logits[0, -1].float() | |
| selected = self.ids[lo:lo + count].to(logits.device) | |
| # Read only the valid candidates and apply the saved FP32 decision bias. | |
| lp = logits.log_softmax(-1).index_select(0, selected) | |
| scores = (lp + self.bias[lo:lo + count].to(logits.device)) / self.decision['temperatures'][kind] | |
| probs = scores.softmax(-1).cpu().tolist() | |
| if any(not math.isfinite(p) for p in probs) or abs(sum(probs) - 1) > 1e-5: | |
| raise RuntimeError('invalid probabilities') | |
| return probs, {'prompt_tokens': len(ids), 'prompt_sha256': hashlib.sha256(text.encode()).hexdigest()} | |
| def predict(self, request): | |
| validate_request(request) | |
| answers, lengths, hashes = {}, {}, {} | |
| for qid, q in request['questions'].items(): | |
| text, kind, keys = prepare_question(request['state'], q, self.decision) | |
| probs, info = self.predict_prompt(text, kind, len(keys)) | |
| answers[qid] = format_answer(kind, keys, probs, q.get('criteria')) | |
| lengths[qid] = info['prompt_tokens'] | |
| hashes[qid] = info['prompt_sha256'] | |
| response = {'id': f'decision-{uuid.uuid4().hex}', 'object': 'structured_decision', | |
| 'created': int(time.time()), 'model': 'Dexy-Decision-9B', 'answers': answers, | |
| 'usage': {'input_tokens': sum(lengths.values()), 'output_tokens': len(answers)}} | |
| if request.get('include_diagnostics', False): | |
| response['diagnostics'] = {'prompt_tokens': lengths, 'prompt_sha256': hashes} | |
| return response | |