Text Generation
Transformers
Safetensors
qwen2_cad_state
cad
text-to-cad
world-model
qwen2
conversational
custom_code
Instructions to use AI-for-CAD/CAD-WAM with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use AI-for-CAD/CAD-WAM with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-generation", model="AI-for-CAD/CAD-WAM", trust_remote_code=True) messages = [ {"role": "user", "content": "Who are you?"}, ] pipe(messages)# pip install -U transformers accelerate # Load model directly from transformers import AutoModelForCausalLM model = AutoModelForCausalLM.from_pretrained("AI-for-CAD/CAD-WAM", trust_remote_code=True, device_map="auto") - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- vLLM
How to use AI-for-CAD/CAD-WAM with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "AI-for-CAD/CAD-WAM" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "AI-for-CAD/CAD-WAM", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }'Use Docker
docker model run hf.co/AI-for-CAD/CAD-WAM
- SGLang
How to use AI-for-CAD/CAD-WAM 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 "AI-for-CAD/CAD-WAM" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "AI-for-CAD/CAD-WAM", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }'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 "AI-for-CAD/CAD-WAM" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "AI-for-CAD/CAD-WAM", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }' - Docker Model Runner
How to use AI-for-CAD/CAD-WAM with Docker Model Runner:
docker model run hf.co/AI-for-CAD/CAD-WAM
Add CAD-WAM weights, model definition and SetVAE encoder
Browse files- .gitattributes +1 -0
- README.md +78 -0
- added_tokens.json +24 -0
- chat_template.jinja +54 -0
- config.json +70 -0
- generation_config.json +14 -0
- geometric_state_embedding.py +56 -0
- merges.txt +0 -0
- model.safetensors +3 -0
- modeling_cadwam.py +322 -0
- setvae_encoder/setvae_encoder.pt +3 -0
- special_tokens_map.json +31 -0
- state_prediction_head.py +31 -0
- tokenizer.json +3 -0
- tokenizer_config.json +207 -0
- vocab.json +0 -0
.gitattributes
CHANGED
|
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
| 36 |
+
tokenizer.json filter=lfs diff=lfs merge=lfs -text
|
README.md
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
license: mit
|
| 3 |
+
library_name: transformers
|
| 4 |
+
pipeline_tag: text-generation
|
| 5 |
+
tags:
|
| 6 |
+
- cad
|
| 7 |
+
- text-to-cad
|
| 8 |
+
- world-model
|
| 9 |
+
- qwen2
|
| 10 |
+
---
|
| 11 |
+
|
| 12 |
+
# CAD-WAM — stepwise text-to-CAD with a geometric world model
|
| 13 |
+
|
| 14 |
+
**Anonymous artifact for a paper currently under double-blind review.** Please do not attempt to
|
| 15 |
+
identify the authors from this repository.
|
| 16 |
+
|
| 17 |
+
CAD-WAM generates a parametric CAD construction sequence from a natural-language description. At every
|
| 18 |
+
step it predicts both the next construction action **and** the geometric state that action will produce,
|
| 19 |
+
and it is re-conditioned on the solid its own actions have actually built: each predicted action is
|
| 20 |
+
executed by a CAD kernel, the resulting solid is sampled and encoded, and that encoding is fed back as the
|
| 21 |
+
state for the next step.
|
| 22 |
+
|
| 23 |
+
- Backbone: Qwen2.5-1.5B-Instruct, extended with a **geometric state embedding** (1024-d latent → 16
|
| 24 |
+
input tokens) and a **state prediction head**.
|
| 25 |
+
- Loss: action cross-entropy + `state_loss_weight` × next-state regression (this checkpoint: `0.03`).
|
| 26 |
+
- Training data: the official DeepCAD split, converted to a step-wise action/state dataset.
|
| 27 |
+
|
| 28 |
+
## Files
|
| 29 |
+
|
| 30 |
+
| file | what it is |
|
| 31 |
+
|---|---|
|
| 32 |
+
| `model.safetensors` | the CAD-WAM weights (BF16, 378 tensors) |
|
| 33 |
+
| `config.json`, `generation_config.json` | architecture and decoding configuration |
|
| 34 |
+
| `modeling_cadwam.py`, `geometric_state_embedding.py`, `state_prediction_head.py` | the model definition, loaded through `trust_remote_code=True` |
|
| 35 |
+
| tokenizer files | unchanged from the backbone, plus the geometric placeholder token |
|
| 36 |
+
| `setvae_encoder/setvae_encoder.pt` | the SetVAE point-cloud encoder that produces the 1024-d geometric state (6.4 M parameters) |
|
| 37 |
+
|
| 38 |
+
## Loading
|
| 39 |
+
|
| 40 |
+
```python
|
| 41 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 42 |
+
|
| 43 |
+
tok = AutoTokenizer.from_pretrained("<repo-id>")
|
| 44 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 45 |
+
"<repo-id>", trust_remote_code=True, dtype="bfloat16"
|
| 46 |
+
).eval()
|
| 47 |
+
```
|
| 48 |
+
|
| 49 |
+
Requires `transformers >= 4.51` (the model definition imports the Qwen3 classes at module scope);
|
| 50 |
+
verified with 4.57.6, the version the checkpoint was trained under.
|
| 51 |
+
|
| 52 |
+
The model is **not** a plain text-to-text model. A forward pass expects a `geo_latent` tensor of shape
|
| 53 |
+
`(batch, 1024)` alongside `input_ids`, and the prompt must contain the geometric placeholder token at the
|
| 54 |
+
16 positions reserved for the state. Encoding a solid into that latent requires the SetVAE encoder in
|
| 55 |
+
`setvae_encoder/`; its architecture, the point-cloud sampling, the CAD kernel executor and the closed-loop
|
| 56 |
+
rollout are in the anonymous code repository linked from the review discussion.
|
| 57 |
+
|
| 58 |
+
For the first step of a construction the state is the empty model, whose latent is the encoder's
|
| 59 |
+
representation of an empty point set.
|
| 60 |
+
|
| 61 |
+
A forward pass returns `logits`, `pred_next_state` (the predicted next geometric state, `(batch, 1024)`),
|
| 62 |
+
`last_hidden_state`, `geo_hidden_states` and `state_repr`.
|
| 63 |
+
|
| 64 |
+
## Intended use and limitations
|
| 65 |
+
|
| 66 |
+
Research artifact for reproducing the paper's results. The action vocabulary covers sketch-and-extrude
|
| 67 |
+
modelling (lines, arcs and circles in a sketch plane, extrusion with boolean union, cut and new-body
|
| 68 |
+
operations); fillet, chamfer, revolve and sketches on created faces are **not** part of this checkpoint's
|
| 69 |
+
representation. Generations are only as valid as the kernel confirms: an action that fails to produce a
|
| 70 |
+
solid is rejected during rollout rather than silently accepted.
|
| 71 |
+
|
| 72 |
+
The checkpoint was trained and evaluated on one corpus of mechanical parts and should not be expected to
|
| 73 |
+
transfer to organic shapes, assemblies or drawings.
|
| 74 |
+
|
| 75 |
+
## License
|
| 76 |
+
|
| 77 |
+
MIT for the released weights and code in this repository. The backbone is Qwen2.5-1.5B-Instruct
|
| 78 |
+
(Apache-2.0); the training data derives from a public CAD corpus under its own terms.
|
added_tokens.json
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"</tool_call>": 151658,
|
| 3 |
+
"<tool_call>": 151657,
|
| 4 |
+
"<|box_end|>": 151649,
|
| 5 |
+
"<|box_start|>": 151648,
|
| 6 |
+
"<|endoftext|>": 151643,
|
| 7 |
+
"<|file_sep|>": 151664,
|
| 8 |
+
"<|fim_middle|>": 151660,
|
| 9 |
+
"<|fim_pad|>": 151662,
|
| 10 |
+
"<|fim_prefix|>": 151659,
|
| 11 |
+
"<|fim_suffix|>": 151661,
|
| 12 |
+
"<|im_end|>": 151645,
|
| 13 |
+
"<|im_start|>": 151644,
|
| 14 |
+
"<|image_pad|>": 151655,
|
| 15 |
+
"<|object_ref_end|>": 151647,
|
| 16 |
+
"<|object_ref_start|>": 151646,
|
| 17 |
+
"<|quad_end|>": 151651,
|
| 18 |
+
"<|quad_start|>": 151650,
|
| 19 |
+
"<|repo_name|>": 151663,
|
| 20 |
+
"<|video_pad|>": 151656,
|
| 21 |
+
"<|vision_end|>": 151653,
|
| 22 |
+
"<|vision_pad|>": 151654,
|
| 23 |
+
"<|vision_start|>": 151652
|
| 24 |
+
}
|
chat_template.jinja
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{%- if tools %}
|
| 2 |
+
{{- '<|im_start|>system\n' }}
|
| 3 |
+
{%- if messages[0]['role'] == 'system' %}
|
| 4 |
+
{{- messages[0]['content'] }}
|
| 5 |
+
{%- else %}
|
| 6 |
+
{{- 'You are Qwen, created by Alibaba Cloud. You are a helpful assistant.' }}
|
| 7 |
+
{%- endif %}
|
| 8 |
+
{{- "\n\n# Tools\n\nYou may call one or more functions to assist with the user query.\n\nYou are provided with function signatures within <tools></tools> XML tags:\n<tools>" }}
|
| 9 |
+
{%- for tool in tools %}
|
| 10 |
+
{{- "\n" }}
|
| 11 |
+
{{- tool | tojson }}
|
| 12 |
+
{%- endfor %}
|
| 13 |
+
{{- "\n</tools>\n\nFor each function call, return a json object with function name and arguments within <tool_call></tool_call> XML tags:\n<tool_call>\n{\"name\": <function-name>, \"arguments\": <args-json-object>}\n</tool_call><|im_end|>\n" }}
|
| 14 |
+
{%- else %}
|
| 15 |
+
{%- if messages[0]['role'] == 'system' %}
|
| 16 |
+
{{- '<|im_start|>system\n' + messages[0]['content'] + '<|im_end|>\n' }}
|
| 17 |
+
{%- else %}
|
| 18 |
+
{{- '<|im_start|>system\nYou are Qwen, created by Alibaba Cloud. You are a helpful assistant.<|im_end|>\n' }}
|
| 19 |
+
{%- endif %}
|
| 20 |
+
{%- endif %}
|
| 21 |
+
{%- for message in messages %}
|
| 22 |
+
{%- if (message.role == "user") or (message.role == "system" and not loop.first) or (message.role == "assistant" and not message.tool_calls) %}
|
| 23 |
+
{{- '<|im_start|>' + message.role + '\n' + message.content + '<|im_end|>' + '\n' }}
|
| 24 |
+
{%- elif message.role == "assistant" %}
|
| 25 |
+
{{- '<|im_start|>' + message.role }}
|
| 26 |
+
{%- if message.content %}
|
| 27 |
+
{{- '\n' + message.content }}
|
| 28 |
+
{%- endif %}
|
| 29 |
+
{%- for tool_call in message.tool_calls %}
|
| 30 |
+
{%- if tool_call.function is defined %}
|
| 31 |
+
{%- set tool_call = tool_call.function %}
|
| 32 |
+
{%- endif %}
|
| 33 |
+
{{- '\n<tool_call>\n{"name": "' }}
|
| 34 |
+
{{- tool_call.name }}
|
| 35 |
+
{{- '", "arguments": ' }}
|
| 36 |
+
{{- tool_call.arguments | tojson }}
|
| 37 |
+
{{- '}\n</tool_call>' }}
|
| 38 |
+
{%- endfor %}
|
| 39 |
+
{{- '<|im_end|>\n' }}
|
| 40 |
+
{%- elif message.role == "tool" %}
|
| 41 |
+
{%- if (loop.index0 == 0) or (messages[loop.index0 - 1].role != "tool") %}
|
| 42 |
+
{{- '<|im_start|>user' }}
|
| 43 |
+
{%- endif %}
|
| 44 |
+
{{- '\n<tool_response>\n' }}
|
| 45 |
+
{{- message.content }}
|
| 46 |
+
{{- '\n</tool_response>' }}
|
| 47 |
+
{%- if loop.last or (messages[loop.index0 + 1].role != "tool") %}
|
| 48 |
+
{{- '<|im_end|>\n' }}
|
| 49 |
+
{%- endif %}
|
| 50 |
+
{%- endif %}
|
| 51 |
+
{%- endfor %}
|
| 52 |
+
{%- if add_generation_prompt %}
|
| 53 |
+
{{- '<|im_start|>assistant\n' }}
|
| 54 |
+
{%- endif %}
|
config.json
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"architectures": [
|
| 3 |
+
"Qwen2ForCADActionState"
|
| 4 |
+
],
|
| 5 |
+
"attention_dropout": 0.0,
|
| 6 |
+
"auto_map": {
|
| 7 |
+
"AutoConfig": "modeling_cadwam.Qwen2CADStateConfig",
|
| 8 |
+
"AutoModelForCausalLM": "modeling_cadwam.Qwen2ForCADActionState"
|
| 9 |
+
},
|
| 10 |
+
"bos_token_id": 151643,
|
| 11 |
+
"dtype": "bfloat16",
|
| 12 |
+
"eos_token_id": 151645,
|
| 13 |
+
"geo_num_heads": 8,
|
| 14 |
+
"geo_num_layers": 2,
|
| 15 |
+
"geo_token_dim": 256,
|
| 16 |
+
"geo_token_id": 151655,
|
| 17 |
+
"hidden_act": "silu",
|
| 18 |
+
"hidden_size": 1536,
|
| 19 |
+
"initializer_range": 0.02,
|
| 20 |
+
"intermediate_size": 8960,
|
| 21 |
+
"latent_dim": 1024,
|
| 22 |
+
"layer_types": [
|
| 23 |
+
"full_attention",
|
| 24 |
+
"full_attention",
|
| 25 |
+
"full_attention",
|
| 26 |
+
"full_attention",
|
| 27 |
+
"full_attention",
|
| 28 |
+
"full_attention",
|
| 29 |
+
"full_attention",
|
| 30 |
+
"full_attention",
|
| 31 |
+
"full_attention",
|
| 32 |
+
"full_attention",
|
| 33 |
+
"full_attention",
|
| 34 |
+
"full_attention",
|
| 35 |
+
"full_attention",
|
| 36 |
+
"full_attention",
|
| 37 |
+
"full_attention",
|
| 38 |
+
"full_attention",
|
| 39 |
+
"full_attention",
|
| 40 |
+
"full_attention",
|
| 41 |
+
"full_attention",
|
| 42 |
+
"full_attention",
|
| 43 |
+
"full_attention",
|
| 44 |
+
"full_attention",
|
| 45 |
+
"full_attention",
|
| 46 |
+
"full_attention",
|
| 47 |
+
"full_attention",
|
| 48 |
+
"full_attention",
|
| 49 |
+
"full_attention",
|
| 50 |
+
"full_attention"
|
| 51 |
+
],
|
| 52 |
+
"max_position_embeddings": 32768,
|
| 53 |
+
"max_window_layers": 21,
|
| 54 |
+
"model_type": "qwen2_cad_state",
|
| 55 |
+
"num_attention_heads": 12,
|
| 56 |
+
"num_geo_tokens": 16,
|
| 57 |
+
"num_hidden_layers": 28,
|
| 58 |
+
"num_key_value_heads": 2,
|
| 59 |
+
"rms_norm_eps": 1e-06,
|
| 60 |
+
"rope_scaling": null,
|
| 61 |
+
"rope_theta": 1000000.0,
|
| 62 |
+
"sliding_window": null,
|
| 63 |
+
"state_intermediate_dim": 2048,
|
| 64 |
+
"state_loss_weight": 0.03,
|
| 65 |
+
"tie_word_embeddings": true,
|
| 66 |
+
"transformers_version": "4.57.1",
|
| 67 |
+
"use_cache": false,
|
| 68 |
+
"use_sliding_window": false,
|
| 69 |
+
"vocab_size": 151936
|
| 70 |
+
}
|
generation_config.json
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"bos_token_id": 151643,
|
| 3 |
+
"do_sample": true,
|
| 4 |
+
"eos_token_id": [
|
| 5 |
+
151645,
|
| 6 |
+
151643
|
| 7 |
+
],
|
| 8 |
+
"pad_token_id": 151643,
|
| 9 |
+
"repetition_penalty": 1.1,
|
| 10 |
+
"temperature": 0.7,
|
| 11 |
+
"top_k": 20,
|
| 12 |
+
"top_p": 0.8,
|
| 13 |
+
"transformers_version": "4.57.1"
|
| 14 |
+
}
|
geometric_state_embedding.py
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""GeometricStateEmbedding — spec §5 (qwen3_8b_cad_state_modification_spec.md).
|
| 2 |
+
|
| 3 |
+
Maps one continuous CAD latent z_t in R^1024 to 16 Qwen-compatible geometric embeddings in R^{16 x 4096}:
|
| 4 |
+
|
| 5 |
+
[B, 1024] -> LayerNorm(1024) -> Linear(1024, 16*256) -> reshape [B, 16, 256]
|
| 6 |
+
-> + learnable slot embeddings [1, 16, 256]
|
| 7 |
+
-> 2-layer bidirectional TransformerEncoder (d=256, 8 heads, FFN 1024, GELU, pre-norm, no causal mask)
|
| 8 |
+
-> LayerNorm(256) -> Linear(256, 4096) -> [B, 16, 4096]
|
| 9 |
+
"""
|
| 10 |
+
import torch
|
| 11 |
+
import torch.nn as nn
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class GeometricStateEmbedding(nn.Module):
|
| 15 |
+
def __init__(
|
| 16 |
+
self,
|
| 17 |
+
latent_dim: int = 1024,
|
| 18 |
+
num_geo_tokens: int = 16,
|
| 19 |
+
geo_token_dim: int = 256,
|
| 20 |
+
qwen_hidden_dim: int = 4096,
|
| 21 |
+
num_layers: int = 2,
|
| 22 |
+
num_heads: int = 8,
|
| 23 |
+
):
|
| 24 |
+
super().__init__()
|
| 25 |
+
self.num_geo_tokens = num_geo_tokens
|
| 26 |
+
self.geo_token_dim = geo_token_dim
|
| 27 |
+
|
| 28 |
+
self.latent_norm = nn.LayerNorm(latent_dim)
|
| 29 |
+
self.expand = nn.Linear(latent_dim, num_geo_tokens * geo_token_dim)
|
| 30 |
+
self.slot_embeddings = nn.Parameter(torch.randn(1, num_geo_tokens, geo_token_dim) * 0.02)
|
| 31 |
+
|
| 32 |
+
encoder_layer = nn.TransformerEncoderLayer(
|
| 33 |
+
d_model=geo_token_dim,
|
| 34 |
+
nhead=num_heads,
|
| 35 |
+
dim_feedforward=geo_token_dim * 4,
|
| 36 |
+
activation="gelu",
|
| 37 |
+
batch_first=True,
|
| 38 |
+
norm_first=True,
|
| 39 |
+
)
|
| 40 |
+
# bidirectional: no mask is ever passed to the encoder (all 16 slots attend to each other)
|
| 41 |
+
self.transformer = nn.TransformerEncoder(encoder_layer, num_layers=num_layers, enable_nested_tensor=False)
|
| 42 |
+
|
| 43 |
+
self.output_norm = nn.LayerNorm(geo_token_dim)
|
| 44 |
+
self.output_proj = nn.Linear(geo_token_dim, qwen_hidden_dim)
|
| 45 |
+
|
| 46 |
+
def forward(self, z: torch.Tensor) -> torch.Tensor:
|
| 47 |
+
# z: [B, latent_dim]
|
| 48 |
+
B = z.shape[0]
|
| 49 |
+
z = self.latent_norm(z)
|
| 50 |
+
x = self.expand(z) # [B, 16*256]
|
| 51 |
+
x = x.view(B, self.num_geo_tokens, self.geo_token_dim) # [B, 16, 256]
|
| 52 |
+
x = x + self.slot_embeddings
|
| 53 |
+
x = self.transformer(x) # [B, 16, 256] (bidirectional)
|
| 54 |
+
x = self.output_norm(x)
|
| 55 |
+
x = self.output_proj(x) # [B, 16, 4096]
|
| 56 |
+
return x
|
merges.txt
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
model.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:a29b49a3ba3136cd5f1ad818e7a354880c1c8502ca092b2628f7d9555af91a19
|
| 3 |
+
size 3577075704
|
modeling_cadwam.py
ADDED
|
@@ -0,0 +1,322 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Qwen3-8B with a continuous CAD-state input branch and an independent next-state head.
|
| 2 |
+
|
| 3 |
+
Implements qwen3_8b_cad_state_modification_spec.md (§2, §6, §8–§13):
|
| 4 |
+
|
| 5 |
+
text (goal + symbolic state) --tokenizer--> input_ids --embed_tokens--> [B, L, 4096]
|
| 6 |
+
geo_latent [B, 1024] --GeometricStateEmbedding--> [B, 16, 4096]
|
| 7 |
+
-> fused at the 16 placeholder positions of the token sequence -> inputs_embeds [B, S, 4096]
|
| 8 |
+
-> ORIGINAL Qwen3-8B backbone (unchanged) -> final hidden states [B, S, 4096]
|
| 9 |
+
-> original LM head (Action Head) -> action logits [B, S, vocab]
|
| 10 |
+
-> hidden states at the 16 geometric positions [B, 16, 4096]
|
| 11 |
+
-> StatePredictionHead (mean pool -> LN -> 4096-2048-1024) -> pred_next_state [B, 1024]
|
| 12 |
+
|
| 13 |
+
The two heads are structurally independent: neither consumes the other's output. Both may back-propagate into
|
| 14 |
+
the shared backbone (no detach). Loss = CE(action) + state_loss_weight * MSE(state, fp32).
|
| 15 |
+
|
| 16 |
+
Fusion uses placeholder tokens: the tokenized sequence must contain exactly `num_geo_tokens` (16) contiguous
|
| 17 |
+
occurrences of `geo_token_id` per sample; their vocabulary embeddings are discarded and replaced by the
|
| 18 |
+
continuous geometric embeddings (spec §6). `insert_geo_placeholders` / `GEO_PLACEHOLDER_TOKEN` help build such
|
| 19 |
+
sequences. Nothing inside the Qwen3 decoder stack is modified.
|
| 20 |
+
|
| 21 |
+
Backbones: the design only needs `hidden_size`, `model.embed_tokens`, `lm_head`, a decoder that accepts
|
| 22 |
+
`inputs_embeds` and the `<|image_pad|>` token, so the same `CADActionStateMixin` sits on top of Qwen3
|
| 23 |
+
(`Qwen3ForCADActionState`) and Qwen2 / Qwen2.5 (`Qwen2ForCADActionState`, used for the backbone-matched comparison
|
| 24 |
+
with Pointer-CAD, which fine-tunes Qwen2.5-Instruct). `cad_state_classes(model_dir)` picks the family from the
|
| 25 |
+
checkpoint's config.json, so training and evaluation code never names a family.
|
| 26 |
+
"""
|
| 27 |
+
import json
|
| 28 |
+
import os
|
| 29 |
+
from dataclasses import dataclass
|
| 30 |
+
from typing import Optional
|
| 31 |
+
|
| 32 |
+
import torch
|
| 33 |
+
import torch.nn as nn
|
| 34 |
+
import torch.nn.functional as F
|
| 35 |
+
from transformers import Qwen2Config, Qwen2ForCausalLM, Qwen3Config, Qwen3ForCausalLM
|
| 36 |
+
from transformers.cache_utils import Cache
|
| 37 |
+
from transformers.models.qwen2.modeling_qwen2 import Qwen2DecoderLayer
|
| 38 |
+
from transformers.models.qwen3.modeling_qwen3 import Qwen3DecoderLayer
|
| 39 |
+
from transformers.utils import ModelOutput
|
| 40 |
+
|
| 41 |
+
from .geometric_state_embedding import GeometricStateEmbedding
|
| 42 |
+
from .state_prediction_head import StatePredictionHead
|
| 43 |
+
|
| 44 |
+
# An existing, otherwise unused special token of the Qwen3 tokenizer is used as the positional marker for the
|
| 45 |
+
# 16 geometric embeddings (spec §6: placeholders are markers only; their vocabulary embeddings are never used).
|
| 46 |
+
# The Qwen2.5 tokenizer has the same token (same id, 151655).
|
| 47 |
+
GEO_PLACEHOLDER_TOKEN = "<|image_pad|>"
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def _set_cad_state_fields(cfg, latent_dim, num_geo_tokens, geo_token_dim, geo_num_layers, geo_num_heads,
|
| 51 |
+
state_intermediate_dim, state_loss_weight, geo_token_id):
|
| 52 |
+
cfg.latent_dim = latent_dim
|
| 53 |
+
cfg.num_geo_tokens = num_geo_tokens
|
| 54 |
+
cfg.geo_token_dim = geo_token_dim
|
| 55 |
+
cfg.geo_num_layers = geo_num_layers
|
| 56 |
+
cfg.geo_num_heads = geo_num_heads
|
| 57 |
+
cfg.state_intermediate_dim = state_intermediate_dim
|
| 58 |
+
cfg.state_loss_weight = state_loss_weight
|
| 59 |
+
cfg.geo_token_id = geo_token_id
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
class Qwen3CADStateConfig(Qwen3Config):
|
| 63 |
+
"""Qwen3Config + the fixed hyper-parameters of the two new modules (spec §14)."""
|
| 64 |
+
model_type = "cadwam"
|
| 65 |
+
|
| 66 |
+
def __init__(
|
| 67 |
+
self,
|
| 68 |
+
latent_dim: int = 1024,
|
| 69 |
+
num_geo_tokens: int = 16,
|
| 70 |
+
geo_token_dim: int = 256,
|
| 71 |
+
geo_num_layers: int = 2,
|
| 72 |
+
geo_num_heads: int = 8,
|
| 73 |
+
state_intermediate_dim: int = 2048,
|
| 74 |
+
state_loss_weight: float = 1.0,
|
| 75 |
+
geo_token_id: Optional[int] = None,
|
| 76 |
+
**kwargs,
|
| 77 |
+
):
|
| 78 |
+
super().__init__(**kwargs)
|
| 79 |
+
_set_cad_state_fields(self, latent_dim, num_geo_tokens, geo_token_dim, geo_num_layers, geo_num_heads,
|
| 80 |
+
state_intermediate_dim, state_loss_weight, geo_token_id)
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
class Qwen2CADStateConfig(Qwen2Config):
|
| 84 |
+
"""Qwen2Config (Qwen2 / Qwen2.5) + the same new-module hyper-parameters as Qwen3CADStateConfig."""
|
| 85 |
+
model_type = "qwen2_cad_state"
|
| 86 |
+
|
| 87 |
+
def __init__(
|
| 88 |
+
self,
|
| 89 |
+
latent_dim: int = 1024,
|
| 90 |
+
num_geo_tokens: int = 16,
|
| 91 |
+
geo_token_dim: int = 256,
|
| 92 |
+
geo_num_layers: int = 2,
|
| 93 |
+
geo_num_heads: int = 8,
|
| 94 |
+
state_intermediate_dim: int = 2048,
|
| 95 |
+
state_loss_weight: float = 1.0,
|
| 96 |
+
geo_token_id: Optional[int] = None,
|
| 97 |
+
**kwargs,
|
| 98 |
+
):
|
| 99 |
+
super().__init__(**kwargs)
|
| 100 |
+
_set_cad_state_fields(self, latent_dim, num_geo_tokens, geo_token_dim, geo_num_layers, geo_num_heads,
|
| 101 |
+
state_intermediate_dim, state_loss_weight, geo_token_id)
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
@dataclass
|
| 105 |
+
class CADActionStateOutput(ModelOutput):
|
| 106 |
+
loss: Optional[torch.FloatTensor] = None
|
| 107 |
+
logits: Optional[torch.FloatTensor] = None # action logits [B, S, vocab]
|
| 108 |
+
pred_next_state: Optional[torch.FloatTensor] = None # predicted next latent [B, 1024]
|
| 109 |
+
action_loss: Optional[torch.FloatTensor] = None
|
| 110 |
+
state_loss: Optional[torch.FloatTensor] = None
|
| 111 |
+
past_key_values: Optional[Cache] = None
|
| 112 |
+
hidden_states: Optional[tuple] = None
|
| 113 |
+
attentions: Optional[tuple] = None
|
| 114 |
+
# interface-inspection extras (not part of the architecture)
|
| 115 |
+
last_hidden_state: Optional[torch.FloatTensor] = None # Qwen final hidden states [B, S, 4096]
|
| 116 |
+
geo_hidden_states: Optional[torch.FloatTensor] = None # geometric final hidden [B, 16, 4096]
|
| 117 |
+
state_repr: Optional[torch.FloatTensor] = None # mean-pooled [B, 4096]
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
class CADActionStateMixin:
|
| 121 |
+
"""Everything the CAD model adds to a Qwen causal LM; placed BEFORE the `*ForCausalLM` base in the MRO."""
|
| 122 |
+
|
| 123 |
+
def _add_cad_state_modules(self, config):
|
| 124 |
+
self.geo_embed = GeometricStateEmbedding(
|
| 125 |
+
latent_dim=config.latent_dim,
|
| 126 |
+
num_geo_tokens=config.num_geo_tokens,
|
| 127 |
+
geo_token_dim=config.geo_token_dim,
|
| 128 |
+
qwen_hidden_dim=config.hidden_size,
|
| 129 |
+
num_layers=config.geo_num_layers,
|
| 130 |
+
num_heads=config.geo_num_heads,
|
| 131 |
+
)
|
| 132 |
+
self.state_head = StatePredictionHead(
|
| 133 |
+
hidden_dim=config.hidden_size,
|
| 134 |
+
intermediate_dim=config.state_intermediate_dim,
|
| 135 |
+
latent_dim=config.latent_dim,
|
| 136 |
+
)
|
| 137 |
+
|
| 138 |
+
# ------------------------------------------------------------------ init of the new modules
|
| 139 |
+
def _init_weights(self, module):
|
| 140 |
+
"""Backbone modules use the backbone's initialisation; the new modules use plain PyTorch defaults
|
| 141 |
+
(needed because from_pretrained materialises missing weights through this hook)."""
|
| 142 |
+
if isinstance(module, nn.MultiheadAttention):
|
| 143 |
+
nn.init.xavier_uniform_(module.in_proj_weight)
|
| 144 |
+
if module.in_proj_bias is not None:
|
| 145 |
+
nn.init.zeros_(module.in_proj_bias)
|
| 146 |
+
nn.init.zeros_(module.out_proj.bias)
|
| 147 |
+
nn.init.xavier_uniform_(module.out_proj.weight)
|
| 148 |
+
elif isinstance(module, nn.LayerNorm):
|
| 149 |
+
nn.init.ones_(module.weight)
|
| 150 |
+
nn.init.zeros_(module.bias)
|
| 151 |
+
elif isinstance(module, GeometricStateEmbedding):
|
| 152 |
+
nn.init.normal_(module.slot_embeddings, std=0.02)
|
| 153 |
+
else:
|
| 154 |
+
super()._init_weights(module)
|
| 155 |
+
|
| 156 |
+
# ------------------------------------------------------------------ helpers
|
| 157 |
+
@property
|
| 158 |
+
def geo_token_id(self) -> int:
|
| 159 |
+
if self.config.geo_token_id is None:
|
| 160 |
+
raise ValueError("config.geo_token_id is not set; call set_geo_token_id(tokenizer) first")
|
| 161 |
+
return self.config.geo_token_id
|
| 162 |
+
|
| 163 |
+
def set_geo_token_id(self, tokenizer, token: str = GEO_PLACEHOLDER_TOKEN):
|
| 164 |
+
tid = tokenizer.convert_tokens_to_ids(token)
|
| 165 |
+
if tid is None or tid == tokenizer.unk_token_id:
|
| 166 |
+
raise ValueError(f"placeholder token {token!r} not in tokenizer vocabulary")
|
| 167 |
+
self.config.geo_token_id = int(tid)
|
| 168 |
+
return self.config.geo_token_id
|
| 169 |
+
|
| 170 |
+
def geo_positions_mask(self, input_ids: torch.LongTensor) -> torch.BoolTensor:
|
| 171 |
+
"""[B, S] bool mask of the 16 contiguous placeholder positions (validated)."""
|
| 172 |
+
mask = input_ids == self.geo_token_id
|
| 173 |
+
n = self.config.num_geo_tokens
|
| 174 |
+
counts = mask.sum(dim=1)
|
| 175 |
+
if not bool((counts == n).all()):
|
| 176 |
+
raise ValueError(f"every sample must contain exactly {n} geo placeholder tokens, got {counts.tolist()}")
|
| 177 |
+
first = mask.float().argmax(dim=1)
|
| 178 |
+
ar = torch.arange(input_ids.shape[1], device=input_ids.device)[None, :]
|
| 179 |
+
contiguous = (ar >= first[:, None]) & (ar < first[:, None] + n)
|
| 180 |
+
if not bool((contiguous == mask).all()):
|
| 181 |
+
raise ValueError("the geo placeholder tokens must form one contiguous block per sample")
|
| 182 |
+
return mask
|
| 183 |
+
|
| 184 |
+
# ------------------------------------------------------------------ forward
|
| 185 |
+
def forward(
|
| 186 |
+
self,
|
| 187 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 188 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 189 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 190 |
+
past_key_values: Optional[Cache] = None,
|
| 191 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 192 |
+
labels: Optional[torch.LongTensor] = None,
|
| 193 |
+
geo_latent: Optional[torch.FloatTensor] = None,
|
| 194 |
+
target_next_state: Optional[torch.FloatTensor] = None,
|
| 195 |
+
use_cache: Optional[bool] = None,
|
| 196 |
+
logits_to_keep: int = 0,
|
| 197 |
+
return_dict: Optional[bool] = None,
|
| 198 |
+
**kwargs,
|
| 199 |
+
) -> CADActionStateOutput:
|
| 200 |
+
# 1) text embeddings from Qwen's embedding table
|
| 201 |
+
if inputs_embeds is None:
|
| 202 |
+
if input_ids is None:
|
| 203 |
+
raise ValueError("input_ids (with geo placeholders) or inputs_embeds is required")
|
| 204 |
+
inputs_embeds = self.model.embed_tokens(input_ids) # [B, S, 4096]
|
| 205 |
+
|
| 206 |
+
# 2-3) geometric embeddings fused at the placeholder positions
|
| 207 |
+
geo_mask = None
|
| 208 |
+
if geo_latent is not None and input_ids is not None:
|
| 209 |
+
has_placeholders = bool((input_ids == self.geo_token_id).any())
|
| 210 |
+
if has_placeholders:
|
| 211 |
+
geo_mask = self.geo_positions_mask(input_ids) # [B, S]
|
| 212 |
+
geo_embeds = self.geo_embed(geo_latent.to(inputs_embeds.dtype)) # [B, 16, 4096]
|
| 213 |
+
inputs_embeds = inputs_embeds.masked_scatter(
|
| 214 |
+
geo_mask.unsqueeze(-1).expand_as(inputs_embeds), geo_embeds.to(inputs_embeds.dtype))
|
| 215 |
+
elif past_key_values is None or past_key_values.get_seq_length() == 0:
|
| 216 |
+
raise ValueError("geo_latent given but input_ids contain no geo placeholder tokens")
|
| 217 |
+
# else: incremental decoding step (KV cache holds the prefix incl. geometry) -> nothing to fuse
|
| 218 |
+
|
| 219 |
+
# 4) original backbone via inputs_embeds
|
| 220 |
+
outputs = self.model(
|
| 221 |
+
input_ids=None,
|
| 222 |
+
attention_mask=attention_mask,
|
| 223 |
+
position_ids=position_ids,
|
| 224 |
+
past_key_values=past_key_values,
|
| 225 |
+
inputs_embeds=inputs_embeds,
|
| 226 |
+
use_cache=use_cache,
|
| 227 |
+
**kwargs,
|
| 228 |
+
)
|
| 229 |
+
hidden_states = outputs.last_hidden_state # [B, S, 4096]
|
| 230 |
+
|
| 231 |
+
# 5) Action Head = original LM head
|
| 232 |
+
slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
|
| 233 |
+
logits = self.lm_head(hidden_states[:, slice_indices, :]) # [B, S', vocab]
|
| 234 |
+
|
| 235 |
+
# 6-7) State Prediction Head on the 16 contextualised geometric hidden states (no detach)
|
| 236 |
+
pred_next_state = geo_hidden = state_repr = None
|
| 237 |
+
if geo_mask is not None:
|
| 238 |
+
B = hidden_states.shape[0]
|
| 239 |
+
geo_hidden = hidden_states[geo_mask].view(B, self.config.num_geo_tokens, -1) # [B, 16, 4096]
|
| 240 |
+
state_repr = self.state_head.pool(geo_hidden) # [B, 4096]
|
| 241 |
+
pred_next_state = self.state_head(geo_hidden) # [B, 1024]
|
| 242 |
+
|
| 243 |
+
# 8) losses
|
| 244 |
+
loss = action_loss = state_loss = None
|
| 245 |
+
if labels is not None:
|
| 246 |
+
action_loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
|
| 247 |
+
loss = action_loss
|
| 248 |
+
if target_next_state is not None and pred_next_state is not None:
|
| 249 |
+
state_loss = F.mse_loss(pred_next_state.float(), target_next_state.float())
|
| 250 |
+
loss = state_loss * self.config.state_loss_weight if loss is None else loss + self.config.state_loss_weight * state_loss
|
| 251 |
+
|
| 252 |
+
return CADActionStateOutput(
|
| 253 |
+
loss=loss,
|
| 254 |
+
logits=logits,
|
| 255 |
+
pred_next_state=pred_next_state,
|
| 256 |
+
action_loss=action_loss,
|
| 257 |
+
state_loss=state_loss,
|
| 258 |
+
past_key_values=outputs.past_key_values,
|
| 259 |
+
hidden_states=outputs.hidden_states,
|
| 260 |
+
attentions=outputs.attentions,
|
| 261 |
+
last_hidden_state=hidden_states,
|
| 262 |
+
geo_hidden_states=geo_hidden,
|
| 263 |
+
state_repr=state_repr,
|
| 264 |
+
)
|
| 265 |
+
|
| 266 |
+
# keep geo_latent flowing through generate() (prefill fuses; cached steps skip fusion)
|
| 267 |
+
def prepare_inputs_for_generation(self, *args, geo_latent=None, **kwargs):
|
| 268 |
+
model_inputs = super().prepare_inputs_for_generation(*args, **kwargs)
|
| 269 |
+
if geo_latent is not None:
|
| 270 |
+
model_inputs["geo_latent"] = geo_latent
|
| 271 |
+
return model_inputs
|
| 272 |
+
|
| 273 |
+
|
| 274 |
+
class Qwen3ForCADActionState(CADActionStateMixin, Qwen3ForCausalLM):
|
| 275 |
+
"""ModifiedQwen3ForCausalLM (spec §13): original backbone + original LM head + GeometricStateEmbedding
|
| 276 |
+
+ StatePredictionHead. Loading a stock Qwen3-8B checkpoint initialises only the two new modules."""
|
| 277 |
+
config_class = Qwen3CADStateConfig
|
| 278 |
+
|
| 279 |
+
def __init__(self, config: Qwen3CADStateConfig):
|
| 280 |
+
super().__init__(config) # self.model (backbone) + self.lm_head (Action Head), unchanged
|
| 281 |
+
self._add_cad_state_modules(config)
|
| 282 |
+
self.post_init()
|
| 283 |
+
|
| 284 |
+
|
| 285 |
+
class Qwen2ForCADActionState(CADActionStateMixin, Qwen2ForCausalLM):
|
| 286 |
+
"""The same CAD model on a Qwen2 / Qwen2.5 backbone. Loading a stock Qwen2.5 checkpoint initialises only
|
| 287 |
+
the two new modules."""
|
| 288 |
+
config_class = Qwen2CADStateConfig
|
| 289 |
+
|
| 290 |
+
def __init__(self, config: Qwen2CADStateConfig):
|
| 291 |
+
super().__init__(config)
|
| 292 |
+
self._add_cad_state_modules(config)
|
| 293 |
+
self.post_init()
|
| 294 |
+
|
| 295 |
+
|
| 296 |
+
_FAMILIES = {
|
| 297 |
+
"qwen3": (Qwen3CADStateConfig, Qwen3ForCADActionState, Qwen3DecoderLayer),
|
| 298 |
+
"cadwam": (Qwen3CADStateConfig, Qwen3ForCADActionState, Qwen3DecoderLayer),
|
| 299 |
+
"qwen2": (Qwen2CADStateConfig, Qwen2ForCADActionState, Qwen2DecoderLayer),
|
| 300 |
+
"qwen2_cad_state": (Qwen2CADStateConfig, Qwen2ForCADActionState, Qwen2DecoderLayer),
|
| 301 |
+
}
|
| 302 |
+
|
| 303 |
+
|
| 304 |
+
def cad_state_classes(model_dir: str):
|
| 305 |
+
"""(ConfigClass, ModelClass, DecoderLayerClass) for a stock Qwen2/2.5/3 checkpoint or a trained CAD one,
|
| 306 |
+
chosen from the `model_type` in its config.json (a local directory or a Hugging Face repo id)."""
|
| 307 |
+
path = os.path.join(model_dir, "config.json")
|
| 308 |
+
if os.path.isfile(path):
|
| 309 |
+
model_type = json.load(open(path)).get("model_type")
|
| 310 |
+
else:
|
| 311 |
+
from transformers import PretrainedConfig
|
| 312 |
+
model_type = PretrainedConfig.get_config_dict(model_dir)[0].get("model_type")
|
| 313 |
+
if model_type not in _FAMILIES:
|
| 314 |
+
raise ValueError(f"{model_dir}: model_type {model_type!r} is not supported "
|
| 315 |
+
f"(expected one of {sorted(_FAMILIES)})")
|
| 316 |
+
return _FAMILIES[model_type]
|
| 317 |
+
|
| 318 |
+
|
| 319 |
+
def insert_geo_placeholders(prefix_text: str, suffix_text: str, num_geo_tokens: int = 16,
|
| 320 |
+
token: str = GEO_PLACEHOLDER_TOKEN) -> str:
|
| 321 |
+
"""Build `prefix + 16 placeholders + suffix` (spec §6: H_input = [H_prefix; H_geo; H_suffix])."""
|
| 322 |
+
return prefix_text + token * num_geo_tokens + suffix_text
|
setvae_encoder/setvae_encoder.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:2a7c146bc50ce281a611f2ebbf80a1447a20c52c4ab1017157a4d2848ff094a8
|
| 3 |
+
size 25710114
|
special_tokens_map.json
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"additional_special_tokens": [
|
| 3 |
+
"<|im_start|>",
|
| 4 |
+
"<|im_end|>",
|
| 5 |
+
"<|object_ref_start|>",
|
| 6 |
+
"<|object_ref_end|>",
|
| 7 |
+
"<|box_start|>",
|
| 8 |
+
"<|box_end|>",
|
| 9 |
+
"<|quad_start|>",
|
| 10 |
+
"<|quad_end|>",
|
| 11 |
+
"<|vision_start|>",
|
| 12 |
+
"<|vision_end|>",
|
| 13 |
+
"<|vision_pad|>",
|
| 14 |
+
"<|image_pad|>",
|
| 15 |
+
"<|video_pad|>"
|
| 16 |
+
],
|
| 17 |
+
"eos_token": {
|
| 18 |
+
"content": "<|im_end|>",
|
| 19 |
+
"lstrip": false,
|
| 20 |
+
"normalized": false,
|
| 21 |
+
"rstrip": false,
|
| 22 |
+
"single_word": false
|
| 23 |
+
},
|
| 24 |
+
"pad_token": {
|
| 25 |
+
"content": "<|endoftext|>",
|
| 26 |
+
"lstrip": false,
|
| 27 |
+
"normalized": false,
|
| 28 |
+
"rstrip": false,
|
| 29 |
+
"single_word": false
|
| 30 |
+
}
|
| 31 |
+
}
|
state_prediction_head.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""StatePredictionHead — spec §9 (qwen3_8b_cad_state_modification_spec.md).
|
| 2 |
+
|
| 3 |
+
geometric final hidden states [B, 16, 4096]
|
| 4 |
+
-> mean pooling over the 16 geometric positions -> [B, 4096]
|
| 5 |
+
-> LayerNorm(4096) -> Linear(4096, 2048) -> GELU -> Linear(2048, 1024) (no output activation)
|
| 6 |
+
-> predicted next latent [B, 1024]
|
| 7 |
+
"""
|
| 8 |
+
import torch
|
| 9 |
+
import torch.nn as nn
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class StatePredictionHead(nn.Module):
|
| 13 |
+
def __init__(self, hidden_dim: int = 4096, intermediate_dim: int = 2048, latent_dim: int = 1024):
|
| 14 |
+
super().__init__()
|
| 15 |
+
self.norm = nn.LayerNorm(hidden_dim)
|
| 16 |
+
self.mlp = nn.Sequential(
|
| 17 |
+
nn.Linear(hidden_dim, intermediate_dim),
|
| 18 |
+
nn.GELU(),
|
| 19 |
+
nn.Linear(intermediate_dim, latent_dim),
|
| 20 |
+
)
|
| 21 |
+
|
| 22 |
+
def pool(self, geo_hidden_states: torch.Tensor) -> torch.Tensor:
|
| 23 |
+
# [B, 16, 4096] -> [B, 4096]
|
| 24 |
+
return geo_hidden_states.mean(dim=1)
|
| 25 |
+
|
| 26 |
+
def forward(self, geo_hidden_states: torch.Tensor) -> torch.Tensor:
|
| 27 |
+
# geo_hidden_states: [B, 16, 4096]
|
| 28 |
+
state_repr = self.pool(geo_hidden_states) # [B, 4096]
|
| 29 |
+
state_repr = self.norm(state_repr)
|
| 30 |
+
pred_next_state = self.mlp(state_repr) # [B, 1024], no activation / normalisation
|
| 31 |
+
return pred_next_state
|
tokenizer.json
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:9c5ae00e602b8860cbd784ba82a8aa14e8feecec692e7076590d014d7b7fdafa
|
| 3 |
+
size 11421896
|
tokenizer_config.json
ADDED
|
@@ -0,0 +1,207 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"add_bos_token": false,
|
| 3 |
+
"add_prefix_space": false,
|
| 4 |
+
"added_tokens_decoder": {
|
| 5 |
+
"151643": {
|
| 6 |
+
"content": "<|endoftext|>",
|
| 7 |
+
"lstrip": false,
|
| 8 |
+
"normalized": false,
|
| 9 |
+
"rstrip": false,
|
| 10 |
+
"single_word": false,
|
| 11 |
+
"special": true
|
| 12 |
+
},
|
| 13 |
+
"151644": {
|
| 14 |
+
"content": "<|im_start|>",
|
| 15 |
+
"lstrip": false,
|
| 16 |
+
"normalized": false,
|
| 17 |
+
"rstrip": false,
|
| 18 |
+
"single_word": false,
|
| 19 |
+
"special": true
|
| 20 |
+
},
|
| 21 |
+
"151645": {
|
| 22 |
+
"content": "<|im_end|>",
|
| 23 |
+
"lstrip": false,
|
| 24 |
+
"normalized": false,
|
| 25 |
+
"rstrip": false,
|
| 26 |
+
"single_word": false,
|
| 27 |
+
"special": true
|
| 28 |
+
},
|
| 29 |
+
"151646": {
|
| 30 |
+
"content": "<|object_ref_start|>",
|
| 31 |
+
"lstrip": false,
|
| 32 |
+
"normalized": false,
|
| 33 |
+
"rstrip": false,
|
| 34 |
+
"single_word": false,
|
| 35 |
+
"special": true
|
| 36 |
+
},
|
| 37 |
+
"151647": {
|
| 38 |
+
"content": "<|object_ref_end|>",
|
| 39 |
+
"lstrip": false,
|
| 40 |
+
"normalized": false,
|
| 41 |
+
"rstrip": false,
|
| 42 |
+
"single_word": false,
|
| 43 |
+
"special": true
|
| 44 |
+
},
|
| 45 |
+
"151648": {
|
| 46 |
+
"content": "<|box_start|>",
|
| 47 |
+
"lstrip": false,
|
| 48 |
+
"normalized": false,
|
| 49 |
+
"rstrip": false,
|
| 50 |
+
"single_word": false,
|
| 51 |
+
"special": true
|
| 52 |
+
},
|
| 53 |
+
"151649": {
|
| 54 |
+
"content": "<|box_end|>",
|
| 55 |
+
"lstrip": false,
|
| 56 |
+
"normalized": false,
|
| 57 |
+
"rstrip": false,
|
| 58 |
+
"single_word": false,
|
| 59 |
+
"special": true
|
| 60 |
+
},
|
| 61 |
+
"151650": {
|
| 62 |
+
"content": "<|quad_start|>",
|
| 63 |
+
"lstrip": false,
|
| 64 |
+
"normalized": false,
|
| 65 |
+
"rstrip": false,
|
| 66 |
+
"single_word": false,
|
| 67 |
+
"special": true
|
| 68 |
+
},
|
| 69 |
+
"151651": {
|
| 70 |
+
"content": "<|quad_end|>",
|
| 71 |
+
"lstrip": false,
|
| 72 |
+
"normalized": false,
|
| 73 |
+
"rstrip": false,
|
| 74 |
+
"single_word": false,
|
| 75 |
+
"special": true
|
| 76 |
+
},
|
| 77 |
+
"151652": {
|
| 78 |
+
"content": "<|vision_start|>",
|
| 79 |
+
"lstrip": false,
|
| 80 |
+
"normalized": false,
|
| 81 |
+
"rstrip": false,
|
| 82 |
+
"single_word": false,
|
| 83 |
+
"special": true
|
| 84 |
+
},
|
| 85 |
+
"151653": {
|
| 86 |
+
"content": "<|vision_end|>",
|
| 87 |
+
"lstrip": false,
|
| 88 |
+
"normalized": false,
|
| 89 |
+
"rstrip": false,
|
| 90 |
+
"single_word": false,
|
| 91 |
+
"special": true
|
| 92 |
+
},
|
| 93 |
+
"151654": {
|
| 94 |
+
"content": "<|vision_pad|>",
|
| 95 |
+
"lstrip": false,
|
| 96 |
+
"normalized": false,
|
| 97 |
+
"rstrip": false,
|
| 98 |
+
"single_word": false,
|
| 99 |
+
"special": true
|
| 100 |
+
},
|
| 101 |
+
"151655": {
|
| 102 |
+
"content": "<|image_pad|>",
|
| 103 |
+
"lstrip": false,
|
| 104 |
+
"normalized": false,
|
| 105 |
+
"rstrip": false,
|
| 106 |
+
"single_word": false,
|
| 107 |
+
"special": true
|
| 108 |
+
},
|
| 109 |
+
"151656": {
|
| 110 |
+
"content": "<|video_pad|>",
|
| 111 |
+
"lstrip": false,
|
| 112 |
+
"normalized": false,
|
| 113 |
+
"rstrip": false,
|
| 114 |
+
"single_word": false,
|
| 115 |
+
"special": true
|
| 116 |
+
},
|
| 117 |
+
"151657": {
|
| 118 |
+
"content": "<tool_call>",
|
| 119 |
+
"lstrip": false,
|
| 120 |
+
"normalized": false,
|
| 121 |
+
"rstrip": false,
|
| 122 |
+
"single_word": false,
|
| 123 |
+
"special": false
|
| 124 |
+
},
|
| 125 |
+
"151658": {
|
| 126 |
+
"content": "</tool_call>",
|
| 127 |
+
"lstrip": false,
|
| 128 |
+
"normalized": false,
|
| 129 |
+
"rstrip": false,
|
| 130 |
+
"single_word": false,
|
| 131 |
+
"special": false
|
| 132 |
+
},
|
| 133 |
+
"151659": {
|
| 134 |
+
"content": "<|fim_prefix|>",
|
| 135 |
+
"lstrip": false,
|
| 136 |
+
"normalized": false,
|
| 137 |
+
"rstrip": false,
|
| 138 |
+
"single_word": false,
|
| 139 |
+
"special": false
|
| 140 |
+
},
|
| 141 |
+
"151660": {
|
| 142 |
+
"content": "<|fim_middle|>",
|
| 143 |
+
"lstrip": false,
|
| 144 |
+
"normalized": false,
|
| 145 |
+
"rstrip": false,
|
| 146 |
+
"single_word": false,
|
| 147 |
+
"special": false
|
| 148 |
+
},
|
| 149 |
+
"151661": {
|
| 150 |
+
"content": "<|fim_suffix|>",
|
| 151 |
+
"lstrip": false,
|
| 152 |
+
"normalized": false,
|
| 153 |
+
"rstrip": false,
|
| 154 |
+
"single_word": false,
|
| 155 |
+
"special": false
|
| 156 |
+
},
|
| 157 |
+
"151662": {
|
| 158 |
+
"content": "<|fim_pad|>",
|
| 159 |
+
"lstrip": false,
|
| 160 |
+
"normalized": false,
|
| 161 |
+
"rstrip": false,
|
| 162 |
+
"single_word": false,
|
| 163 |
+
"special": false
|
| 164 |
+
},
|
| 165 |
+
"151663": {
|
| 166 |
+
"content": "<|repo_name|>",
|
| 167 |
+
"lstrip": false,
|
| 168 |
+
"normalized": false,
|
| 169 |
+
"rstrip": false,
|
| 170 |
+
"single_word": false,
|
| 171 |
+
"special": false
|
| 172 |
+
},
|
| 173 |
+
"151664": {
|
| 174 |
+
"content": "<|file_sep|>",
|
| 175 |
+
"lstrip": false,
|
| 176 |
+
"normalized": false,
|
| 177 |
+
"rstrip": false,
|
| 178 |
+
"single_word": false,
|
| 179 |
+
"special": false
|
| 180 |
+
}
|
| 181 |
+
},
|
| 182 |
+
"additional_special_tokens": [
|
| 183 |
+
"<|im_start|>",
|
| 184 |
+
"<|im_end|>",
|
| 185 |
+
"<|object_ref_start|>",
|
| 186 |
+
"<|object_ref_end|>",
|
| 187 |
+
"<|box_start|>",
|
| 188 |
+
"<|box_end|>",
|
| 189 |
+
"<|quad_start|>",
|
| 190 |
+
"<|quad_end|>",
|
| 191 |
+
"<|vision_start|>",
|
| 192 |
+
"<|vision_end|>",
|
| 193 |
+
"<|vision_pad|>",
|
| 194 |
+
"<|image_pad|>",
|
| 195 |
+
"<|video_pad|>"
|
| 196 |
+
],
|
| 197 |
+
"bos_token": null,
|
| 198 |
+
"clean_up_tokenization_spaces": false,
|
| 199 |
+
"eos_token": "<|im_end|>",
|
| 200 |
+
"errors": "replace",
|
| 201 |
+
"extra_special_tokens": {},
|
| 202 |
+
"model_max_length": 131072,
|
| 203 |
+
"pad_token": "<|endoftext|>",
|
| 204 |
+
"split_special_tokens": false,
|
| 205 |
+
"tokenizer_class": "Qwen2Tokenizer",
|
| 206 |
+
"unk_token": null
|
| 207 |
+
}
|
vocab.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|