NyxKrage commited on
Commit
ca700c7
·
verified ·
0 Parent(s):
Files changed (38) hide show
  1. .gitattributes +35 -0
  2. LICENSE.md +27 -0
  3. README.md +96 -0
  4. chat_template.jinja +75 -0
  5. config.json +68 -0
  6. configuration_moondream3.py +299 -0
  7. convert_moondream_weights_to_hf.py +239 -0
  8. image_processing_moondream3.py +274 -0
  9. model.safetensors +3 -0
  10. modeling_moondream3.py +1054 -0
  11. modeling_moondream3_fusedmoe.py +301 -0
  12. moondream3_moe_fused/functional.py +79 -0
  13. moondream3_moe_fused/grouped_gemm/LICENSE +661 -0
  14. moondream3_moe_fused/grouped_gemm/__init__.py +0 -0
  15. moondream3_moe_fused/grouped_gemm/__pycache__/__init__.cpython-311.pyc +0 -0
  16. moondream3_moe_fused/grouped_gemm/__pycache__/autotuning.cpython-311.pyc +0 -0
  17. moondream3_moe_fused/grouped_gemm/__pycache__/backward_dw.cpython-311.pyc +0 -0
  18. moondream3_moe_fused/grouped_gemm/__pycache__/forward.cpython-311.pyc +0 -0
  19. moondream3_moe_fused/grouped_gemm/__pycache__/forward_transposed.cpython-311.pyc +0 -0
  20. moondream3_moe_fused/grouped_gemm/__pycache__/interface.cpython-311.pyc +0 -0
  21. moondream3_moe_fused/grouped_gemm/autotuning.py +111 -0
  22. moondream3_moe_fused/grouped_gemm/backward_dw.py +135 -0
  23. moondream3_moe_fused/grouped_gemm/forward.py +164 -0
  24. moondream3_moe_fused/grouped_gemm/forward_4bit.py +209 -0
  25. moondream3_moe_fused/grouped_gemm/forward_transposed.py +152 -0
  26. moondream3_moe_fused/grouped_gemm/interface.py +31 -0
  27. moondream3_moe_fused/kernels/__init__.py +0 -0
  28. moondream3_moe_fused/kernels/indexing.py +65 -0
  29. moondream3_moe_fused/lora.py +143 -0
  30. moondream3_moe_fused/moe_fused_linear.py +44 -0
  31. moondream3_moe_fused/quantize/layer.py +96 -0
  32. moondream3_moe_fused/quantize/quantizer.py +133 -0
  33. preprocessor_config.json +10 -0
  34. processing_moondream3.py +256 -0
  35. processor_config.json +7 -0
  36. special_tokens_map.json +10 -0
  37. tokenizer.json +0 -0
  38. tokenizer_config.json +180 -0
.gitattributes ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz 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
LICENSE.md ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ | License | Business Source License (BSL 1.1) |
2
+ | --- | --- |
3
+ | Licensor | M87 Labs, Inc. |
4
+ | Licensed Work | “Moondream 3 (Preview)” including Model Weights and any Derivatives (“Derivatives” include fine-tunes, merges, quantizations, weight deltas, and other weight-level modifications or conversions.) |
5
+ | Additional Use Grant | You may make production use of the Licensed Work, provided Your use does not include offering the Licensed Work to third parties on a hosted or embedded basis in order to compete with M87 Labs’s paid version(s) of the Licensed Work. For purposes of this license:<br><br>A “competitive offering” is a Product that is offered to third parties on a paid basis, including through paid support arrangements, that significantly overlaps with the capabilities of M87 Labs’s paid version(s) of the Licensed Work. If Your Product is not a competitive offering when You first make it generally available, it will not become a competitive offering later due to M87 Labs releasing a new version of the Licensed Work with additional capabilities. In addition, Products that are not provided on a paid basis are not competitive.<br><br>“Product” means software that is offered to end users to manage in their own environments or offered as a service on a hosted basis.<br><br>“Embedded” means including the source code or executable code from the Licensed Work in a competitive offering. “Embedded” also means packaging the competitive offering in such a way that the Licensed Work must be accessed or downloaded for the competitive offering to operate.<br><br>Hosting or using the Licensed Work(s) for internal purposes within an organization is not considered a competitive offering. M87 Labs considers your organization to include all of your affiliates under common control. |
6
+ | Change Date | Two years after the first public release of this version of the Licensed Work |
7
+ | Change License | Apache License, Version 2.0 |
8
+
9
+ For information about alternative licensing arrangements for the Licensed Work, please contact [contact@m87.ai](mailto:contact@m87.ai).
10
+
11
+ The text of the Business Source License 1.1 follows. License text copyright (c) 2020 MariaDB Corporation Ab, All Rights Reserved. “Business Source License” is a trademark of MariaDB Corporation Ab.
12
+
13
+ ## Terms
14
+
15
+ The Licensor hereby grants you the right to copy, modify, create derivative works, redistribute, and make non-production use of the Licensed Work. The Licensor may make an Additional Use Grant, above, permitting limited production use.
16
+
17
+ Effective on the Change Date, or the fourth anniversary of the first publicly available distribution of a specific version of the Licensed Work under this License, whichever comes first, the Licensor hereby grants you rights under the terms of the Change License, and the rights granted in the paragraph above terminate.
18
+
19
+ If your use of the Licensed Work does not comply with the requirements currently in effect as described in this License, you must purchase a commercial license from the Licensor, its affiliated entities, or authorized resellers, or you must refrain from using the Licensed Work.
20
+
21
+ All copies of the original and modified Licensed Work, and derivative works of the Licensed Work, are subject to this License. This License applies separately for each version of the Licensed Work and the Change Date may vary for each version of the Licensed Work released by Licensor.
22
+
23
+ You must conspicuously display this License on each original or modified copy of the Licensed Work. If you receive the Licensed Work in original or modified form from a third party, the terms and conditions set forth in this License apply to your use of that work.
24
+
25
+ Any use of the Licensed Work in violation of this License will automatically terminate your rights under this License for the current and all other versions of the Licensed Work.
26
+
27
+ This License does not grant you any right in any trademark or logo of Licensor or its affiliates (provided that you may use a trademark or logo of Licensor as expressly required by this License).TO THE EXTENT PERMITTED BY APPLICABLE LAW, THE LICENSED WORK IS PROVIDED ON AN “AS IS” BASIS. LICENSOR HEREBY DISCLAIMS ALL WARRANTIES AND CONDITIONS, EXPRESS OR IMPLIED, INCLUDING (WITHOUT LIMITATION) WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT, AND TITLE.
README.md ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ library_name: transformers
3
+ pipeline_tag: image-text-to-text
4
+ license: other
5
+ ---
6
+
7
+ # Moondream 3 HF
8
+
9
+ **Moondream 3 HF** is a reimplementation of the [Moondream 3 (Preview)](https://huggingface.co/moondream/moondream3-preview) model using the standard Hugging Face Transformers architecture conventions.
10
+
11
+ ## Overview
12
+
13
+ - Multimodal vision-language model with a mixture-of-experts (MoE) text backbone
14
+ - Architecture and weights correspond to Moondream 3 (Preview) (approximately 9B parameters, 2B active)
15
+ - Implemented as standard Transformers components:
16
+ - `Moondream3ForConditionalGeneration`
17
+ - `Moondream3Model`, `Moondream3TextModel`, `Moondream3VisionModel`
18
+ - `Moondream3Processor`, `Moondream3ImageProcessor`, `Moondream3Config`
19
+
20
+ The purpose of this repository is to make Moondream 3 interoperable with the Hugging Face ecosystem so it can be used directly with the Transformers API, including `generate()`, `Trainer`, and PEFT integrations.
21
+
22
+ ## Example usage
23
+
24
+ Example for running multimodal inference with the `moondream3-hf` implementation:
25
+
26
+ ```python
27
+ import torch
28
+ from PIL import Image
29
+ from transformers import AutoProcessor, AutoModelForCausalLM
30
+
31
+ DEVICE="cuda:0"
32
+
33
+ model = AutoModelForCausalLM.from_pretrained("NyxKrage/moondream3-hf", dtype="bfloat16", device_map=DEVICE, trust_remote_code=True)
34
+ processor = AutoProcessor.from_pretrained("NyxKrage/moondream3-hf", use_fast=False, trust_remote_code=True)
35
+
36
+
37
+ image1 = Image.open("image1.jpg")
38
+ image2 = Image.open("image2.jpg")
39
+ text = [processor.apply_chat_template("", tokenize=False)] * 2
40
+ inputs = processor(text=text, images=[
41
+ image1,
42
+ image2,
43
+ ])
44
+ inputs = {k: v.to(DEVICE) for k,v in inputs.items()}
45
+
46
+ model.eval()
47
+
48
+ with torch.no_grad():
49
+ outputs = model.generate(
50
+ **inputs,
51
+ use_cache=True,
52
+ )
53
+ outputs = [
54
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs["input_ids"], outputs)
55
+ ]
56
+ for output in outputs:
57
+ print(processor.decode(output))
58
+
59
+ ```
60
+
61
+ The `chat_template` uses Hugging Face’s Jinja format and accepts either a single string or a sequence of messages (`user [, assistant]`).
62
+
63
+ ### Training
64
+
65
+ The model can be trained using `trl` and supports `peft` and `bitsandbytes` out of the box.
66
+ Included in the repo is also an implementation which replaces the MoE layers with a grouped_gemm implementation which has been adapted from [github:woct0rdho/transformers-qwen3-moe-fused](https://github.com/woct0rdho/transformers-qwen3-moe-fused), and can be used by importing Moondream3ForConditionalGeneration from `modeling_moondream3_fusedmoe.py` instead.
67
+
68
+
69
+ ## Prompting modes
70
+
71
+ The chat template supports multiple task types via text prefixes:
72
+
73
+ | Mode | Template prefix | Example input |
74
+ | ------- | ----------------------------- | ----------------------------------------- |
75
+ | Query | `query:` | `query: What is happening in this image?` |
76
+ | Caption | `caption:[short/normal/long]` | `caption: long` |
77
+ | Detect | `detect:` | `detect: dog` |
78
+ | Point | `point:` | `point: red car` |
79
+
80
+ If no prefix is provided, the default mode is `query:`.
81
+
82
+ This reimplementation aims to provide interoperability and ease of experimentation within the Hugging Face ecosystem. It is not an official release.
83
+
84
+ ## License
85
+
86
+ The model weights remain under the **Business Source License 1.1 with an Additional Use Grant (No Third-Party Service)**, identical to the original [Moondream 3 Preview license](https://huggingface.co/moondream/moondream3-preview/blob/main/LICENSE.md).
87
+
88
+ This allows research, personal, and most commercial use, but prohibits offering hosted or resold access that competes with M87 Labs’ paid services.
89
+
90
+ All new implementation code in this repository is released under the **Apache 2.0 License**.
91
+
92
+ ## Credits
93
+
94
+ * Original model and research: M87 Labs / Moondream AI
95
+ * Hugging Face–compatible reimplementation: NyxKrage
96
+ * Based on the public [Moondream 3 Preview](https://huggingface.co/moondream/moondream3-preview) release
chat_template.jinja ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {# Accepts:
2
+ - messages as a single string
3
+ - messages as 1-2 chat dicts: user[, assistant]
4
+ - user.content may be a string OR a list with exactly one {type:text} and one {type:image}
5
+ #}
6
+ {% if messages is string -%}
7
+ {% set text = messages | trim -%}
8
+ {% set has_assistant = false -%}
9
+ {%- else -%}
10
+ {% if messages | length < 1 or messages | length > 2 -%}
11
+ {{ raise_exception("Provide a single string or 1-2 messages (user[, assistant]).") }}
12
+ {%- endif -%}
13
+ {% if (messages[0].get('role') | default('')) != 'user' -%}
14
+ {{ raise_exception("First message must have role 'user'.") }}
15
+ {%- endif -%}
16
+ {% if messages | length == 2 and (messages[1].get('role') | default('')) != 'assistant' -%}
17
+ {{ raise_exception("Second message, if present, must have role 'assistant'.") }}
18
+ {%- endif -%}
19
+
20
+ {# Extract user text, supporting multimodal content #}
21
+ {% set ucontent = messages[0]['content'] | default('', true) -%}
22
+ {% if ucontent is string -%}
23
+ {% set text = ucontent | trim -%}
24
+ {%- else -%}
25
+ {% if ucontent | length != 2 -%}
26
+ {{ raise_exception("User content list must have exactly two parts: one text and one image.") }}
27
+ {%- endif -%}
28
+ {% set text_parts = ucontent | selectattr('type','equalto','text') | list -%}
29
+ {% set image_parts = ucontent | selectattr('type','equalto','image') | list -%}
30
+ {% if (text_parts | length) != 1 or (image_parts | length) != 1 -%}
31
+ {{ raise_exception("User content must include exactly one text and one image part.") }}
32
+ {%- endif -%}
33
+ {% set text = (text_parts[0].get('text') | default('')) | trim -%}
34
+ {%- endif -%}
35
+
36
+ {# Extract assistant text if present (string or list of parts) #}
37
+ {% set has_assistant = (messages | length == 2) -%}
38
+ {% if has_assistant -%}
39
+ {% set acontent = messages[1]['content'] | default('', true) -%}
40
+ {% if acontent is string -%}
41
+ {% set assistant_text = acontent -%}
42
+ {%- else -%}
43
+ {% set atexts = acontent | selectattr('type','equalto','text') | map(attribute='text') | list -%}
44
+ {% set assistant_text = (atexts | join('')) -%}
45
+ {%- endif -%}
46
+ {%- endif -%}
47
+ {%- endif -%}
48
+
49
+ {% set lower = text | lower -%}
50
+
51
+ {# Routing with zero-whitespace outputs #}
52
+ {% if text == '' -%}
53
+ <|md_reserved_0|>describe<|md_reserved_1|>normal<|md_reserved_2|>
54
+ {%- elif lower.startswith('caption:') -%}
55
+ {% set length = (text[8:] | trim | lower) -%}
56
+ {% if length not in ['short','normal','long'] -%}
57
+ {{ raise_exception("caption length must be one of: short, normal, long.") }}
58
+ {%- endif -%}
59
+ <|md_reserved_0|>describe<|md_reserved_1|>{{ length }}<|md_reserved_2|>
60
+ {%- elif lower.startswith('query:') -%}
61
+ {% set q = text[6:] | trim -%}
62
+ <|md_reserved_0|>query<|md_reserved_1|>{{ q }}<|md_reserved_2|>
63
+ {%- elif lower.startswith('detect:') -%}
64
+ {% set q = text[7:] | trim -%}
65
+ <|md_reserved_0|>det<|md_reserved_1|>{{ q }}<|md_reserved_2|>
66
+ {%- elif lower.startswith('point:') -%}
67
+ {% set q = text[6:] | trim -%}
68
+ <|md_reserved_0|>point<|md_reserved_1|>{{ q }}<|md_reserved_2|>
69
+ {%- else -%}
70
+ {% set q = text -%}
71
+ <|md_reserved_0|>query<|md_reserved_1|>{{ q }}<|md_reserved_2|>
72
+ {%- endif -%}
73
+ {%- generation -%}
74
+ {%- if has_assistant -%}{{ assistant_text }}{{ eos_token }}{%- endif -%}
75
+ {%- endgeneration -%}
config.json ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "Moondream3ForConditonalGeneration"
4
+ ],
5
+ "auto_map": {
6
+ "AutoConfig": "configuration_moondream3.Moondream3Config",
7
+ "AutoModel": "modeling_moondream3.Moondream3Model",
8
+ "AutoModelForCausalLM": "modeling_moondream3.Moondream3ForConditionalGeneration"
9
+ },
10
+ "model_type": "moondream3",
11
+ "region_config": {
12
+ "coord_feat_dim": 256,
13
+ "coord_out_dim": 1024,
14
+ "hidden_size": 2048,
15
+ "model_type": "moondream3_region",
16
+ "size_feat_dim": 512,
17
+ "size_out_dim": 2048
18
+ },
19
+ "text_config": {
20
+ "attention_bias": true,
21
+ "attention_dropout": 0.0,
22
+ "head_dim": 64,
23
+ "hidden_act": "silu",
24
+ "hidden_size": 2048,
25
+ "initializer_range": 0.02,
26
+ "intermediate_size": 8192,
27
+ "max_position_embeddings": 4096,
28
+ "model_type": "moondream3_text",
29
+ "moe_intermediate_size": 1024,
30
+ "moe_start_layer": 4,
31
+ "num_attention_heads": 32,
32
+ "num_experts": 64,
33
+ "num_experts_per_tok": 8,
34
+ "num_hidden_layers": 24,
35
+ "num_key_value_heads": 32,
36
+ "num_local_experts": 64,
37
+ "output_router_logits": false,
38
+ "prefix_attn": 730,
39
+ "bos_token_id": 0,
40
+ "rms_norm_eps": 1e-06,
41
+ "rope_parameters": {
42
+ "rope_theta": 1500000.0,
43
+ "rope_type": "default"
44
+ },
45
+ "use_cache": true,
46
+ "vocab_size": 51200
47
+ },
48
+ "tie_word_embeddings": false,
49
+ "transformers_version": "5.0.0.dev0",
50
+ "vision_config": {
51
+ "attention_bias": true,
52
+ "attention_dropout": 0.0,
53
+ "crop_size": 378,
54
+ "hidden_act": "gelu_pytorch_tanh",
55
+ "hidden_size": 1152,
56
+ "in_channels": 3,
57
+ "initializer_range": 0.02,
58
+ "intermediate_size": 4304,
59
+ "max_crops": 12,
60
+ "model_type": "moondream3_vision",
61
+ "num_attention_heads": 16,
62
+ "num_hidden_layers": 27,
63
+ "overlap_margin": 4,
64
+ "patch_size": 14,
65
+ "proj_inner_dim": 8192,
66
+ "proj_out_dim": 2048
67
+ }
68
+ }
configuration_moondream3.py ADDED
@@ -0,0 +1,299 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2025 The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ from typing import Optional, List
17
+
18
+ from transformers.configuration_utils import PretrainedConfig
19
+ from transformers.modeling_rope_utils import rope_config_validation
20
+
21
+
22
+ class Moondream3TextConfig(PretrainedConfig):
23
+ r"""
24
+ This is the configuration class to store the configuration of a [`Moondream3TextModel`]. It is used to instantiate a
25
+ Moondream3 model according to the specified arguments, defining the model architecture.
26
+
27
+ Configuration objects inherit from [`PreTrainedConfig`] and can be used to control the model outputs. Read the
28
+ documentation from [`PreTrainedConfig`] for more information.
29
+
30
+ Args:
31
+ vocab_size (`int`, *optional*, defaults to 51200):
32
+ Vocabulary size of the Moondream3 model.
33
+ hidden_size (`int`, *optional*, defaults to 2048):
34
+ Dimension of the hidden representations.
35
+ intermediate_size (`int`, *optional*, defaults to 8192):
36
+ Dimension of the MLP representations.
37
+ num_hidden_layers (`int`, *optional*, defaults to 24):
38
+ Number of hidden layers in the Transformer encoder.
39
+ num_attention_heads (`int`, *optional*, defaults to 32):
40
+ Number of attention heads for each attention layer in the Transformer encoder.
41
+ num_key_value_heads (`int`, *optional*, defaults to 32):
42
+ This is the number of key_value heads that should be used to implement Grouped Query Attention.
43
+ max_position_embeddings (`int`, *optional*, defaults to 4096):
44
+ The maximum sequence length that this model might ever be used with.
45
+ num_experts (`int`, *optional*, defaults to 64):
46
+ Number of experts for MoE layers.
47
+ num_experts_per_tok (`int`, *optional*, defaults to 8):
48
+ Number of selected experts per token.
49
+ moe_intermediate_size (`int`, *optional*, defaults to 1024):
50
+ Intermediate size of the routed expert.
51
+ moe_start_layer (`int`, *optional*, defaults to 4):
52
+ The layer index where MoE layers start.
53
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
54
+ The non-linear activation function.
55
+ initializer_range (`float`, *optional*, defaults to 0.02):
56
+ The standard deviation of the truncated_normal_initializer.
57
+ rms_norm_eps (`float`, *optional*, defaults to 1e-6):
58
+ The epsilon used by the rms normalization layers.
59
+ use_cache (`bool`, *optional*, defaults to `True`):
60
+ Whether or not the model should return the last key/values attentions.
61
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
62
+ Whether the model's input and output word embeddings should be tied.
63
+ attention_bias (`bool`, *optional*, defaults to `False`):
64
+ Whether to use a bias in the query, key, value and output projection layers.
65
+ head_dim (`int`, *optional*):
66
+ The dimension of the head. If not specified, will default to `hidden_size // num_attention_heads`.
67
+ """
68
+
69
+ model_type = "moondream3_text"
70
+ base_config_key = "text_config"
71
+ keys_to_ignore_at_inference = ["past_key_values"]
72
+
73
+ def __init__(
74
+ self,
75
+ vocab_size: int = 51200,
76
+ hidden_size: int = 2048,
77
+ intermediate_size: int = 8192,
78
+ num_hidden_layers: int = 24,
79
+ num_attention_heads: int = 32,
80
+ num_key_value_heads: int = 32,
81
+ max_position_embeddings: int = 4096,
82
+ num_experts: int = 64,
83
+ num_experts_per_tok: int = 8,
84
+ moe_intermediate_size: int = 1024,
85
+ moe_start_layer: int = 4,
86
+ bos_id: int = 0,
87
+ hidden_act: str = "silu",
88
+ initializer_range: float = 0.02,
89
+ rms_norm_eps: float = 1e-5,
90
+ use_cache: bool = False,
91
+ tie_word_embeddings: bool = False,
92
+ attention_bias: bool = True,
93
+ rope_parameters: Optional[dict] = None,
94
+ head_dim: Optional[int] = None,
95
+ **kwargs,
96
+ ):
97
+ self.vocab_size = vocab_size
98
+ self.max_position_embeddings = max_position_embeddings
99
+ self.hidden_size = hidden_size
100
+ self.intermediate_size = intermediate_size
101
+ self.num_hidden_layers = num_hidden_layers
102
+ self.num_attention_heads = num_attention_heads
103
+ self.num_key_value_heads = num_key_value_heads
104
+ self.hidden_act = hidden_act
105
+ self.initializer_range = initializer_range
106
+ self.rms_norm_eps = rms_norm_eps
107
+ self.use_cache = use_cache
108
+ self.attention_bias = attention_bias
109
+ self.head_dim = head_dim or hidden_size // num_attention_heads
110
+ self.bos_id = bos_id
111
+
112
+ # MoE parameters (merged from TextMoeConfig)
113
+ self.num_experts = num_experts
114
+ self.num_experts_per_tok = num_experts_per_tok
115
+ self.moe_intermediate_size = moe_intermediate_size
116
+ self.moe_start_layer = moe_start_layer
117
+
118
+
119
+ # Try to set `rope_scaling` if available, otherwise use `rope_parameters`
120
+ rope_scaling = kwargs.pop("rope_scaling", None)
121
+ self.rope_parameters = rope_scaling or rope_parameters
122
+
123
+ # Validate the correctness of rotary position embeddings parameters
124
+ rope_theta = kwargs.get("rope_theta", 1500000.0)
125
+ rope_config_validation(self)
126
+
127
+ # HF compatibility attributes
128
+ self.output_router_logits = False
129
+ self.output_attentions = False
130
+ self.output_hidden_states = False
131
+ self.attention_dropout = 0.0
132
+
133
+ super().__init__(tie_word_embeddings=tie_word_embeddings, **kwargs)
134
+
135
+
136
+ class Moondream3VisionConfig(PretrainedConfig):
137
+ r"""
138
+ This is the configuration class to store the configuration of the Moondream3 vision encoder.
139
+
140
+ Args:
141
+ hidden_size (`int`, *optional*, defaults to 1152):
142
+ Dimension of the encoder's hidden states.
143
+ intermediate_size (`int`, *optional*, defaults to 4304):
144
+ Dimension of the encoder's MLP representations.
145
+ num_hidden_layers (`int`, *optional*, defaults to 27):
146
+ Number of hidden layers in the vision encoder.
147
+ num_attention_heads (`int`, *optional*, defaults to 16):
148
+ Number of attention heads in the vision encoder.
149
+ patch_size (`int`, *optional*, defaults to 14):
150
+ The size of each patch in the vision encoder.
151
+ in_channels (`int`, *optional*, defaults to 3):
152
+ Number of input channels.
153
+ proj_out_dim (`int`, *optional*, defaults to 2048):
154
+ Output dimension of the projection layer.
155
+ crop_size (`int`, *optional*, defaults to 378):
156
+ Size of image crops.
157
+ max_crops (`int`, *optional*, defaults to 12):
158
+ Maximum number of crops.
159
+ overlap_margin (`int`, *optional*, defaults to 4):
160
+ Overlap margin for crops.
161
+ proj_inner_dim (`int`, *optional*, defaults to 8192):
162
+ Inner dimension of the projection MLP.
163
+ hidden_act (`str`, *optional*, defaults to `"gelu_pytorch_tanh"`):
164
+ The non-linear activation function.
165
+ initializer_range (`float`, *optional*, defaults to 0.02):
166
+ The standard deviation of the truncated_normal_initializer.
167
+ """
168
+ model_type = "moondream3_vision"
169
+ base_config_key = "vision_config"
170
+
171
+ def __init__(
172
+ self,
173
+ hidden_size: int = 1152,
174
+ intermediate_size: int = 4304,
175
+ num_hidden_layers: int = 27,
176
+ num_attention_heads: int = 16,
177
+ patch_size: int = 14,
178
+ in_channels: int = 3,
179
+ proj_out_dim: int = 2048,
180
+ crop_size: int = 378,
181
+ max_crops: int = 12,
182
+ overlap_margin: int = 4,
183
+ proj_inner_dim: int = 8192,
184
+ prefix_len: int = 730,
185
+ hidden_act: str = "gelu_pytorch_tanh",
186
+ initializer_range: float = 0.02,
187
+ attention_bias: bool = True,
188
+ **kwargs,
189
+ ):
190
+ self.hidden_size = hidden_size
191
+ self.intermediate_size = intermediate_size
192
+ self.num_hidden_layers = num_hidden_layers
193
+ self.num_attention_heads = num_attention_heads
194
+ self.patch_size = patch_size
195
+ self.in_channels = in_channels
196
+ self.proj_out_dim = proj_out_dim
197
+ self.crop_size = crop_size
198
+ self.max_crops = max_crops
199
+ self.prefix_len = prefix_len
200
+ self.overlap_margin = overlap_margin
201
+ self.proj_inner_dim = proj_inner_dim
202
+ self.hidden_act = hidden_act
203
+ self.initializer_range = initializer_range
204
+ self.attention_dropout = 0.0
205
+ self.attention_bias = attention_bias
206
+
207
+ super().__init__(**kwargs)
208
+
209
+
210
+ class Moondream3RegionConfig(PretrainedConfig):
211
+ r"""
212
+ This is the configuration class to store the configuration of the Moondream3 region encoder for object detection and grounding.
213
+
214
+ Args:
215
+ hidden_size (`int`, *optional*, defaults to 2048):
216
+ Dimension of the hidden representations for region features.
217
+ coord_feat_dim (`int`, *optional*, defaults to 256):
218
+ Dimension of coordinate feature embeddings.
219
+ coord_out_dim (`int`, *optional*, defaults to 1024):
220
+ Output dimension for coordinate features.
221
+ size_feat_dim (`int`, *optional*, defaults to 512):
222
+ Dimension of size feature embeddings.
223
+ size_out_dim (`int`, *optional*, defaults to 2048):
224
+ Output dimension for size features.
225
+ """
226
+ model_type = "moondream3_region"
227
+ base_config_key = "region_config"
228
+
229
+ def __init__(
230
+ self,
231
+ hidden_size: int = 2048,
232
+ coord_feat_dim: int = 256,
233
+ coord_out_dim: int = 1024,
234
+ size_feat_dim: int = 512,
235
+ size_out_dim: int = 2048,
236
+ **kwargs,
237
+ ):
238
+ super().__init__(**kwargs)
239
+
240
+ self.hidden_size = hidden_size
241
+ self.coord_feat_dim = coord_feat_dim
242
+ self.coord_out_dim = coord_out_dim
243
+ self.size_feat_dim = size_feat_dim
244
+ self.size_out_dim = size_out_dim
245
+
246
+
247
+ class Moondream3Config(PretrainedConfig):
248
+ r"""
249
+ This is the configuration class to store the configuration of a [`Moondream3Model`].
250
+
251
+ Args:
252
+ text_config (`Union[PreTrainedConfig, dict]`, *optional*, defaults to `Moondream3TextConfig`):
253
+ The config object or dictionary of the text backbone.
254
+ vision_config (`Union[PreTrainedConfig, dict]`, *optional*, defaults to `Moondream3VisionConfig`):
255
+ The config object or dictionary of the vision backbone.
256
+ region_config (`Union[PreTrainedConfig, dict]`, *optional*, defaults to `Moondream3RegionConfig`):
257
+ The config object or dictionary of the region backbone for object detection and grounding.
258
+ image_token_id (`int`, *optional*, defaults to 151655):
259
+ The image token index to encode the image prompt.
260
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
261
+ Whether to tie the word embeddings.
262
+ """
263
+
264
+ model_type = "moondream3"
265
+ sub_configs = {
266
+ "vision_config": Moondream3VisionConfig,
267
+ "text_config": Moondream3TextConfig,
268
+ "region_config": Moondream3RegionConfig,
269
+ }
270
+ keys_to_ignore_at_inference = ["past_key_values"]
271
+
272
+ def __init__(
273
+ self,
274
+ text_config=None,
275
+ vision_config=None,
276
+ region_config=None,
277
+ bos_token_id=0,
278
+ tie_word_embeddings: bool = False,
279
+ **kwargs,
280
+ ):
281
+ if isinstance(vision_config, dict):
282
+ self.vision_config = self.sub_configs["vision_config"](**vision_config)
283
+ elif vision_config is None:
284
+ self.vision_config = self.sub_configs["vision_config"]()
285
+
286
+ if isinstance(text_config, dict):
287
+ self.text_config = self.sub_configs["text_config"](**text_config)
288
+ elif text_config is None:
289
+ self.text_config = self.sub_configs["text_config"]()
290
+
291
+ if isinstance(region_config, dict):
292
+ self.region_config = self.sub_configs["region_config"](**region_config)
293
+ elif region_config is None:
294
+ self.region_config = self.sub_configs["region_config"]()
295
+
296
+ super().__init__(**kwargs, tie_word_embeddings=tie_word_embeddings)
297
+
298
+
299
+ __all__ = ["Moondream3Config", "Moondream3TextConfig", "Moondream3VisionConfig", "Moondream3RegionConfig"]
convert_moondream_weights_to_hf.py ADDED
@@ -0,0 +1,239 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # coding=utf-8
3
+ # Copyright 2025 The HuggingFace Inc. team. All rights reserved.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+
17
+ import argparse
18
+ import json
19
+ import re
20
+ from pathlib import Path
21
+ from typing import Dict
22
+
23
+ from safetensors.torch import load_file
24
+ from safetensors.torch import save_file
25
+
26
+
27
+ # Key mapping from original Moondream to HF Moondream3
28
+ OLD_KEY_TO_NEW_KEY_MAPPING = [
29
+ # Text model
30
+ (r"model\.text\.wte", "model.text_model.embed_tokens.weight"),
31
+ (r"model\.text\.post_ln\.(weight|bias)", r"model.text_model.norm.\1"),
32
+ (r"model\.text\.lm_head\.(weight|bias)", r"lm_head.\1"),
33
+ (r"model\.text\.blocks\.(\d+)\.attn\.qkv\.(weight|bias)", r"model.text_model.layers.\1.self_attn.qkv.\2"),
34
+ (r"model\.text\.blocks\.(\d+)\.attn\.proj\.(weight|bias)", r"model.text_model.layers.\1.self_attn.o_proj.\2"),
35
+ (r"model\.text\.blocks\.(\d+)\.attn\.tau\.wq", r"model.text_model.layers.\1.self_attn.tau_wq.weight"),
36
+ (r"model\.text\.blocks\.(\d+)\.attn\.tau\.wv", r"model.text_model.layers.\1.self_attn.tau_wv.weight"),
37
+ (r"model\.text\.blocks\.(\d+)\.attn\.tau\.alpha", r"model.text_model.layers.\1.self_attn.tau_alpha"),
38
+ (r"model\.text\.blocks\.(\d+)\.ln\.(weight|bias)", r"model.text_model.layers.\1.input_layernorm.\2"),
39
+ (r"model\.text\.blocks\.(\d+)\.mlp\.fc1\.(weight|bias)", r"model.text_model.layers.\1.mlp.up_proj.\2"),
40
+ (r"model\.text\.blocks\.(\d+)\.mlp\.fc2\.(weight|bias)", r"model.text_model.layers.\1.mlp.down_proj.\2"),
41
+ (r"model\.text\.blocks\.(\d+)\.mlp\.router\.(weight|bias)", r"model.text_model.layers.\1.mlp.gate.\2"),
42
+
43
+ # Vision model
44
+ (r"model\.vision\.patch_emb\.(weight|bias)", r"model.vision_model.embeddings.projection.\1"),
45
+ (r"model\.vision\.pos_emb", "model.vision_model.embeddings.position_embeddings"),
46
+ (r"model\.vision\.post_ln\.(weight|bias)", r"model.vision_model.post_layernorm.\1"),
47
+ (r"model\.vision\.blocks\.(\d+)\.attn\.qkv\.(weight|bias)", r"model.vision_model.layers.\1.self_attn.qkv.\2"),
48
+ (r"model\.vision\.blocks\.(\d+)\.attn\.proj\.(weight|bias)", r"model.vision_model.layers.\1.self_attn.o_proj.\2"),
49
+ (r"model\.vision\.blocks\.(\d+)\.ln1\.(weight|bias)", r"model.vision_model.layers.\1.input_layernorm.\2"),
50
+ (r"model\.vision\.blocks\.(\d+)\.ln2\.(weight|bias)", r"model.vision_model.layers.\1.post_attention_layernorm.\2"),
51
+ (r"model\.vision\.blocks\.(\d+)\.mlp\.fc1\.(weight|bias)", r"model.vision_model.layers.\1.mlp.up_proj.\2"),
52
+ (r"model\.vision\.blocks\.(\d+)\.mlp\.fc2\.(weight|bias)", r"model.vision_model.layers.\1.mlp.down_proj.\2"),
53
+
54
+ # Vision projection
55
+ (r"model\.vision\.proj_mlp\.fc1\.(weight|bias)", r"model.vision_model.vision_projection.up_proj.\1"),
56
+ (r"model\.vision\.proj_mlp\.fc2\.(weight|bias)", r"model.vision_model.vision_projection.down_proj.\1"),
57
+
58
+ # Region model
59
+ (r"model\.region\.coord_encoder\.(weight|bias)", r"model.region_encoder.coord_encoder.\1"),
60
+ (r"model\.region\.coord_decoder\.(weight|bias)", r"model.region_decoder.coord_decoder.\1"),
61
+ (r"model\.region\.size_encoder\.(weight|bias)", r"model.region_encoder.size_encoder.\1"),
62
+ (r"model\.region\.size_decoder\.(weight|bias)", r"model.region_decoder.size_decoder.\1"),
63
+ (r"model\.region\.coord_features", "model.region_encoder.coord_freq"),
64
+ (r"model\.region\.size_features", "model.region_encoder.size_freq"),
65
+ ]
66
+
67
+
68
+ def rename_key(old_key: str) -> str:
69
+ """Convert original key name to HF key name."""
70
+ for pattern, new_key in OLD_KEY_TO_NEW_KEY_MAPPING:
71
+ if re.match(pattern, old_key):
72
+ return re.sub(pattern, new_key, old_key)
73
+ return old_key
74
+
75
+
76
+ def convert_state_dict(original_state_dict: Dict) -> Dict:
77
+ """Convert original state dict to HF format."""
78
+ converted_state_dict = {}
79
+ converted_keys = []
80
+ for old_key, tensor in original_state_dict.items():
81
+ new_key = rename_key(old_key)
82
+ print(old_key, new_key)
83
+
84
+ # Handle QKV weight splitting for attention
85
+ if "attn.qkv.weight" in old_key or "attn.qkv.bias" in old_key:
86
+ # Split QKV into separate Q, K, V matrices
87
+ layer_match = re.search(r"blocks\.(\d+)", old_key)
88
+ if layer_match:
89
+ layer_idx = int(layer_match.group(1))
90
+
91
+ # Determine if this is text or vision model
92
+ if "model.text.blocks" in old_key:
93
+ n_heads = 32
94
+ n_kv_heads = 32
95
+ head_dim = 64 # 2048 / 32
96
+ base_key = f"model.text_model.layers.{layer_idx}.self_attn"
97
+ else: # vision
98
+ n_heads = 16
99
+ n_kv_heads = 16
100
+ head_dim = 72 # 1152 / 16
101
+ base_key = f"model.vision_model.layers.{layer_idx}.self_attn"
102
+
103
+ # Split tensor
104
+ q_dim = n_heads * head_dim
105
+ kv_dim = n_kv_heads * head_dim
106
+
107
+ if "weight" in old_key:
108
+ q_weight = tensor[:q_dim]
109
+ k_weight = tensor[q_dim:q_dim + kv_dim]
110
+ v_weight = tensor[q_dim + kv_dim:]
111
+
112
+ converted_state_dict[f"{base_key}.q_proj.weight"] = q_weight
113
+ converted_state_dict[f"{base_key}.k_proj.weight"] = k_weight
114
+ converted_state_dict[f"{base_key}.v_proj.weight"] = v_weight
115
+ converted_keys.append(old_key)
116
+ else: # bias
117
+ q_bias = tensor[:q_dim]
118
+ k_bias = tensor[q_dim:q_dim + kv_dim]
119
+ v_bias = tensor[q_dim + kv_dim:]
120
+
121
+ converted_state_dict[f"{base_key}.q_proj.bias"] = q_bias
122
+ converted_state_dict[f"{base_key}.k_proj.bias"] = k_bias
123
+ converted_state_dict[f"{base_key}.v_proj.bias"] = v_bias
124
+ converted_keys.append(old_key)
125
+ # Handle MoE expert weight splitting
126
+ elif ("mlp.fc1.weight" in old_key or "mlp.fc2.weight" in old_key) and not "proj_mlp" in old_key:
127
+ layer_match = re.search(r"blocks\.(\d+)", old_key)
128
+ if layer_match:
129
+ layer_idx = int(layer_match.group(1))
130
+ # Only process MoE layers (4+ in this model)
131
+ if layer_idx >= 4 and "model.text." in old_key:
132
+ n_experts = 64 # From config
133
+
134
+ if "fc1.weight" in old_key:
135
+ # Shape: (n_experts, 2 * d_ffn, d_model) → split into individual experts
136
+ for expert_idx in range(n_experts):
137
+ expert_weight = tensor[expert_idx] # Shape: (2 * d_ffn, d_model)
138
+ # For GeGLU, split into gate and up projections
139
+ up_weight = expert_weight[:expert_weight.shape[0]//2] # First half
140
+ gate_weight = expert_weight[expert_weight.shape[0]//2:] # Second half
141
+
142
+ converted_state_dict[f"model.text_model.layers.{layer_idx}.mlp.experts.{expert_idx}.gate_proj.weight"] = gate_weight
143
+ converted_state_dict[f"model.text_model.layers.{layer_idx}.mlp.experts.{expert_idx}.up_proj.weight"] = up_weight
144
+ elif "fc2.weight" in old_key:
145
+ # Shape: (n_experts, d_model, d_ffn) → split into individual experts
146
+ for expert_idx in range(n_experts):
147
+ expert_weight = tensor[expert_idx] # Shape: (d_model, d_ffn)
148
+ converted_state_dict[f"model.text_model.layers.{layer_idx}.mlp.experts.{expert_idx}.down_proj.weight"] = expert_weight
149
+ else:
150
+ # Dense MLP for layers < 4
151
+ converted_state_dict[new_key] = tensor
152
+ else:
153
+ converted_state_dict[new_key] = tensor
154
+ return converted_state_dict
155
+
156
+
157
+ def convert_moondream_weights_to_hf(
158
+ original_model_path: str,
159
+ output_file: str,
160
+ ):
161
+ """Convert Moondream weights to HuggingFace format."""
162
+
163
+ # Load original state dict
164
+ print(f"Loading original model from {original_model_path}")
165
+
166
+ # Find safetensors files
167
+ model_path = Path(original_model_path)
168
+ if model_path.is_file() and model_path.suffix == ".safetensors":
169
+ # Single file
170
+ original_state_dict = load_file(str(model_path))
171
+ elif model_path.is_dir():
172
+ # Directory - look for index file or single model file
173
+ index_path = model_path / "model.safetensors.index.json"
174
+ single_file_path = model_path / "model.safetensors"
175
+
176
+ if index_path.exists():
177
+ with open(index_path) as f:
178
+ index = json.load(f)
179
+
180
+ original_state_dict = {}
181
+ for filename in set(index["weight_map"].values()):
182
+ file_path = model_path / filename
183
+ if file_path.exists():
184
+ state_dict = load_file(str(file_path))
185
+ for k, v in state_dict.items():
186
+ original_state_dict[k] = v
187
+ else:
188
+ print(f"Warning: {file_path} not found")
189
+ elif single_file_path.exists():
190
+ original_state_dict = load_file(str(single_file_path))
191
+ else:
192
+ raise FileNotFoundError(f"Could not find model files in {original_model_path}")
193
+ else:
194
+ raise FileNotFoundError(f"Could not find model files in {original_model_path}")
195
+
196
+ print(f"Loaded {len(original_state_dict)} tensors")
197
+
198
+ # Convert state dict
199
+ print("Converting state dict...")
200
+ converted_state_dict = convert_state_dict(original_state_dict)
201
+
202
+ print(f"Converted {len(converted_state_dict)} tensors")
203
+
204
+ # Save converted weights
205
+ output_path = Path(output_file)
206
+ output_path.parent.mkdir(parents=True, exist_ok=True)
207
+
208
+ print(f"Saving converted weights to {output_path}")
209
+ save_file(converted_state_dict, str(output_path))
210
+
211
+ print("Conversion complete!")
212
+ print(f"Converted weights saved to {output_path}")
213
+
214
+
215
+ def main():
216
+ parser = argparse.ArgumentParser(description="Convert Moondream weights to HuggingFace format")
217
+ parser.add_argument(
218
+ "--input_path",
219
+ type=str,
220
+ required=True,
221
+ help="Path to original Moondream model directory or safetensors file",
222
+ )
223
+ parser.add_argument(
224
+ "--output_file",
225
+ type=str,
226
+ required=True,
227
+ help="Path to save converted HuggingFace safetensors file",
228
+ )
229
+
230
+ # args = parser.parse_args()
231
+
232
+ convert_moondream_weights_to_hf(
233
+ "moondream/", # args.input_path,
234
+ "moondream3/model.safetensors", # args.output_file,
235
+ )
236
+
237
+
238
+ if __name__ == "__main__":
239
+ main()
image_processing_moondream3.py ADDED
@@ -0,0 +1,274 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Image processor class for Moondream3."""
16
+
17
+ import math
18
+ from typing import Optional, Union
19
+
20
+ import torch
21
+ import numpy as np
22
+
23
+ from transformers.image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
24
+ from transformers.image_utils import (
25
+ ImageInput,
26
+ make_flat_list_of_images,
27
+ valid_images,
28
+ validate_kwargs,
29
+ )
30
+ from transformers.processing_utils import ImagesKwargs
31
+ from transformers.utils import TensorType, logging
32
+ from transformers.utils.import_utils import requires_backends
33
+
34
+
35
+ logger = logging.get_logger(__name__)
36
+
37
+
38
+ import PIL
39
+
40
+
41
+ class Moondream3ImageProcessorKwargs(ImagesKwargs, total=False):
42
+ """
43
+ patch_size (`Union[dict[str, int], int]` *optional*, defaults to `{"height": 16, "width": 16}`):
44
+ Size of the patches in the model, used to calculate the output image size. Can be overridden by `patch_size` in the `preprocess` method.
45
+ """
46
+ pass
47
+
48
+ def select_tiling(
49
+ height: int, width: int, crop_size: int, max_crops: int
50
+ ) -> tuple[int, int]:
51
+ """
52
+ Determine the optimal number of tiles to cover an image with overlapping crops.
53
+ """
54
+ if height <= crop_size or width <= crop_size:
55
+ return (1, 1)
56
+
57
+ # Minimum required tiles in each dimension
58
+ min_h = math.ceil(height / crop_size)
59
+ min_w = math.ceil(width / crop_size)
60
+
61
+ # If minimum required tiles exceed max_crops, return proportional distribution
62
+ if min_h * min_w > max_crops:
63
+ ratio = math.sqrt(max_crops / (min_h * min_w))
64
+ return (max(1, math.floor(min_h * ratio)), max(1, math.floor(min_w * ratio)))
65
+
66
+ # Perfect aspect-ratio tiles that satisfy max_crops
67
+ h_tiles = math.floor(math.sqrt(max_crops * height / width))
68
+ w_tiles = math.floor(math.sqrt(max_crops * width / height))
69
+
70
+ # Ensure we meet minimum tile requirements
71
+ h_tiles = max(h_tiles, min_h)
72
+ w_tiles = max(w_tiles, min_w)
73
+
74
+ # If we exceeded max_crops, scale down the larger dimension
75
+ if h_tiles * w_tiles > max_crops:
76
+ if w_tiles > h_tiles:
77
+ w_tiles = math.floor(max_crops / h_tiles)
78
+ else:
79
+ h_tiles = math.floor(max_crops / w_tiles)
80
+
81
+ return (max(1, h_tiles), max(1, w_tiles))
82
+
83
+
84
+ def overlap_crop_image(
85
+ image: np.ndarray,
86
+ overlap_margin: int,
87
+ max_crops: int,
88
+ base_size: tuple[int, int] = (378, 378),
89
+ patch_size: int = 14,
90
+ ):
91
+ """
92
+ Process an image using an overlap-and-resize cropping strategy with margin handling.
93
+
94
+ This function takes an input image and creates multiple overlapping crops with
95
+ consistent margins. It produces:
96
+ 1. A single global crop resized to base_size
97
+ 2. Multiple overlapping local crops that maintain high resolution details
98
+ 3. A patch ordering matrix that tracks correspondence between crops
99
+
100
+ The overlap strategy ensures:
101
+ - Smooth transitions between adjacent crops
102
+ - No loss of information at crop boundaries
103
+ - Proper handling of features that cross crop boundaries
104
+ - Consistent patch indexing across the full image
105
+
106
+ Args:
107
+ image (np.ndarray): Input image as numpy array with shape (H,W,C)
108
+ base_size (tuple[int,int]): Target size for crops, default (378,378)
109
+ patch_size (int): Size of patches in pixels, default 14
110
+ overlap_margin (int): Margin size in patch units, default 4
111
+ max_crops (int): Maximum number of crops allowed, default 12
112
+
113
+ Returns:
114
+ OverlapCropOutput: Dictionary containing:
115
+ - crops: A numpy array containing the global crop of the full image (index 0)
116
+ followed by the overlapping cropped regions (indices 1+)
117
+ - tiling: Tuple of (height,width) tile counts
118
+ """
119
+ original_h, original_w = image.shape[:2]
120
+
121
+ # Convert margin from patch units to pixels
122
+ margin_pixels = patch_size * overlap_margin
123
+ total_margin_pixels = margin_pixels * 2 # Both sides
124
+
125
+ # Calculate crop parameters
126
+ crop_patches = base_size[0] // patch_size # patches per crop dimension
127
+ crop_window_patches = crop_patches - (2 * overlap_margin) # usable patches
128
+ crop_window_size = crop_window_patches * patch_size # usable size in pixels
129
+
130
+ # Determine tiling
131
+ tiling = select_tiling(
132
+ original_h - total_margin_pixels,
133
+ original_w - total_margin_pixels,
134
+ crop_window_size,
135
+ max_crops,
136
+ )
137
+
138
+ # Pre-allocate crops.
139
+ n_crops = tiling[0] * tiling[1] + 1 # 1 = global crop
140
+ crops = np.zeros(
141
+ (n_crops, base_size[0], base_size[1], image.shape[2]), dtype=np.uint8
142
+ )
143
+
144
+ # Resize image to fit tiling
145
+ target_size = (
146
+ tiling[0] * crop_window_size + total_margin_pixels,
147
+ tiling[1] * crop_window_size + total_margin_pixels,
148
+ )
149
+
150
+ # if HAS_VIPS:
151
+ # # Convert to vips for resizing
152
+ # vips_image = pyvips.Image.new_from_array(image)
153
+ # scale_x = target_size[1] / image.shape[1]
154
+ # scale_y = target_size[0] / image.shape[0]
155
+ # resized = vips_image.resize(scale_x, vscale=scale_y)
156
+ # image = resized.numpy()
157
+
158
+ # # Create global crop
159
+ # scale_x = base_size[1] / vips_image.width
160
+ # scale_y = base_size[0] / vips_image.height
161
+ # global_vips = vips_image.resize(scale_x, vscale=scale_y)
162
+ # crops[0] = global_vips.numpy()
163
+ # else:
164
+ # Fallback to PIL
165
+ pil_img = PIL.Image.fromarray(image)
166
+ resized = pil_img.resize(
167
+ (int(target_size[1]), int(target_size[0])),
168
+ resample=PIL.Image.Resampling.LANCZOS,
169
+ )
170
+ image = np.asarray(resized)
171
+
172
+ # Create global crop
173
+ global_pil = pil_img.resize(
174
+ (int(base_size[1]), int(base_size[0])), resample=PIL.Image.Resampling.LANCZOS
175
+ )
176
+ crops[0] = np.asarray(global_pil)
177
+
178
+ for i in range(tiling[0]):
179
+ for j in range(tiling[1]):
180
+ # Calculate crop coordinates
181
+ y0 = i * crop_window_size
182
+ x0 = j * crop_window_size
183
+
184
+ # Extract crop with padding if needed
185
+ y_end = min(y0 + base_size[0], image.shape[0])
186
+ x_end = min(x0 + base_size[1], image.shape[1])
187
+
188
+ crop_region = image[y0:y_end, x0:x_end]
189
+ crops[
190
+ 1 + i * tiling[1] + j, : crop_region.shape[0], : crop_region.shape[1]
191
+ ] = crop_region
192
+
193
+ return {"crops": crops, "tiling": tiling}
194
+
195
+ def prepare_crops(image, max_crops=12, overlap_margin=4):
196
+ if isinstance(image, PIL.Image.Image):
197
+ np_image = np.array(image.convert("RGB"))
198
+ elif isinstance(image, torch.Tensor):
199
+ np_image = image.cpu().detach().numpy()
200
+ else:
201
+ np_image = image
202
+ overlap_crops = overlap_crop_image(
203
+ np_image, max_crops=max_crops, overlap_margin=overlap_margin
204
+ )
205
+ all_crops = overlap_crops["crops"]
206
+ all_crops = np.transpose(all_crops, (0, 3, 1, 2))
207
+ all_crops = (((all_crops / 255.0) - 0.5) / 0.5)
208
+ return all_crops.tolist(), overlap_crops["tiling"]
209
+
210
+ class Moondream3ImageProcessor(BaseImageProcessor):
211
+ r"""
212
+ Constructs a Moondream3 image processor.
213
+ """
214
+
215
+ model_input_names = ["pixel_values", "image_sizes"]
216
+ valid_kwargs = Moondream3ImageProcessorKwargs
217
+
218
+ def __init__(
219
+ self,
220
+ max_crops: int = 12,
221
+ overlap_margin: int = 4,
222
+ **kwargs,
223
+ ) -> None:
224
+ super().__init__(**kwargs)
225
+ self.max_crops = max_crops
226
+ self.overlap_margin = overlap_margin
227
+ self._valid_processor_keys = [
228
+ "max_crops",
229
+ "overlap_margin",
230
+ ]
231
+
232
+ def preprocess(
233
+ self,
234
+ images: ImageInput,
235
+ max_crops: Optional[int] = None,
236
+ overlap_margin: Optional[int] = None,
237
+ return_tensors: Optional[Union[str, TensorType]] = None,
238
+ **kwargs,
239
+ ) -> PIL.Image.Image:
240
+ """
241
+ Preprocess an image or batch of images.
242
+
243
+ Args:
244
+ images (`ImageInput`):
245
+ Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If
246
+ passing in images with pixel values between 0 and 1, set `do_rescale=False`.
247
+ max_crops (`bool`, *optional*, defaults to `self.max_crops`):
248
+ overlap_margin (`dict[str, int]`, *optional*, defaults to `self.overlap_margin`):
249
+ """
250
+ overlap_margin = overlap_margin if overlap_margin is not None else self.overlap_margin
251
+ max_crops = max_crops if max_crops is not None else self.max_crops
252
+
253
+ validate_kwargs(captured_kwargs=kwargs.keys(), valid_processor_keys=self._valid_processor_keys)
254
+
255
+ images = self.fetch_images(images)
256
+ images = make_flat_list_of_images(images)
257
+
258
+ if not valid_images(images[0]):
259
+ raise ValueError("Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, or torch.Tensor")
260
+
261
+ batch_images = []
262
+ batch_tiling = []
263
+ for image in images:
264
+ pixel_values, tiling = prepare_crops(image, max_crops=max_crops, overlap_margin=overlap_margin)
265
+ batch_images.append(pixel_values)
266
+ batch_tiling.append(tiling)
267
+
268
+
269
+ return BatchFeature(
270
+ data={"pixel_values": batch_images, "tiling": batch_tiling}, tensor_type=return_tensors
271
+ )
272
+
273
+
274
+ __all__ = ["Moondream3ImageProcessor"]
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d1b992dcf85d87a027b8af4317ceb860768cba70f921d8ab60a2de2d49d8ccf3
3
+ size 18537874416
modeling_moondream3.py ADDED
@@ -0,0 +1,1054 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2025 The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ from typing import Callable, Optional, Tuple, Union
17
+
18
+ import numpy as np
19
+
20
+ import torch
21
+ import torch.nn as nn
22
+ import torch.nn.functional as F
23
+
24
+ from PIL import Image
25
+
26
+ from transformers.activations import ACT2FN
27
+ from transformers.cache_utils import Cache, DynamicCache
28
+ from transformers.masking_utils import create_causal_mask
29
+ from transformers.modeling_outputs import (
30
+ BaseModelOutputWithPast,
31
+ CausalLMOutputWithPast,
32
+ )
33
+ from transformers.processing_utils import Unpack
34
+ from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
35
+ from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
36
+ from transformers.generation import GenerationMixin
37
+ from transformers.utils import logging, TransformersKwargs
38
+ from .configuration_moondream3 import Moondream3Config, Moondream3TextConfig, Moondream3VisionConfig, Moondream3RegionConfig
39
+
40
+ logger = logging.get_logger(__name__)
41
+
42
+ _CONFIG_FOR_DOC = "Moondream3Config"
43
+
44
+ def rotate_half(x):
45
+ """Rotates half the hidden dims of the input."""
46
+ x1 = x[..., : x.shape[-1] // 2]
47
+ x2 = x[..., x.shape[-1] // 2 :]
48
+ return torch.cat((-x2, x1), dim=-1)
49
+
50
+
51
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
52
+ """Applies Rotary Position Embedding to the query and key tensors.
53
+
54
+ Args:
55
+ q (`torch.Tensor`): The query tensor.
56
+ k (`torch.Tensor`): The key tensor.
57
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
58
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
59
+ position_ids (`torch.Tensor`, *optional*):
60
+ Deprecated and unused.
61
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
62
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
63
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
64
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
65
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
66
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
67
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
68
+ Returns:
69
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
70
+ """
71
+ rot_dim = cos.shape[-1]
72
+
73
+ def rotate_prefix(x):
74
+ x_rot = x[..., :rot_dim]
75
+ x_pass = x[..., rot_dim:]
76
+ x_rot = (x_rot * cos) + (rotate_half(x_rot) * sin)
77
+ return torch.cat([x_rot, x_pass], dim=-1)
78
+
79
+ cos = cos.unsqueeze(unsqueeze_dim)
80
+ sin = sin.unsqueeze(unsqueeze_dim)
81
+
82
+ return rotate_prefix(q), rotate_prefix(k)
83
+
84
+ class Moondream3RotaryEmbedding(nn.Module):
85
+ inv_freq: torch.Tensor # fix linting for `register_buffer`
86
+
87
+ def __init__(self, config: Moondream3Config, device=None):
88
+ super().__init__()
89
+ self.max_seq_len_cached = config.max_position_embeddings
90
+ self.original_max_seq_len = config.max_position_embeddings
91
+
92
+ self.config = config
93
+
94
+ self.rope_type = self.config.rope_parameters["rope_type"]
95
+ rope_init_fn: Callable = self.compute_default_rope_parameters
96
+ if self.rope_type != "default":
97
+ rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
98
+ inv_freq, self.attention_scaling = rope_init_fn(self.config, device)
99
+
100
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
101
+ self.original_inv_freq = inv_freq
102
+
103
+ @staticmethod
104
+ def compute_default_rope_parameters(
105
+ config: Optional[Moondream3Config] = None,
106
+ device: Optional["torch.device"] = None,
107
+ seq_len: Optional[int] = None,
108
+ ) -> tuple["torch.Tensor", float]:
109
+ """
110
+ Computes the inverse frequencies according to the original RoPE implementation
111
+ Args:
112
+ config ([`~transformers.PreTrainedConfig`]):
113
+ The model configuration.
114
+ device (`torch.device`):
115
+ The device to use for initialization of the inverse frequencies.
116
+ seq_len (`int`, *optional*):
117
+ The current sequence length. Unused for this type of RoPE.
118
+ Returns:
119
+ Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
120
+ post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).
121
+ """
122
+ base = config.rope_parameters["rope_theta"]
123
+ dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads
124
+ dim = dim // 2
125
+
126
+ attention_factor = 1.0 # Unused in this type of RoPE
127
+
128
+ # Compute the inverse frequencies
129
+ inv_freq = 1.0 / (
130
+ base ** (torch.arange(0, dim, 2, dtype=torch.float).to(device=device)[: (dim // 2)] / dim)
131
+ )
132
+ return inv_freq, attention_factor
133
+
134
+ @torch.no_grad()
135
+ @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
136
+ def forward(self, x, position_ids):
137
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
138
+ position_ids_expanded = position_ids[:, None, :].float()
139
+
140
+ device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
141
+ with torch.autocast(device_type=device_type, enabled=False): # Force float32
142
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
143
+ emb = torch.cat((freqs, freqs), dim=-1)
144
+ cos = emb.cos() * self.attention_scaling
145
+ sin = emb.sin() * self.attention_scaling
146
+
147
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
148
+
149
+
150
+ class Moondream3Attention(nn.Module):
151
+ def __init__(self, config: Moondream3TextConfig | Moondream3VisionConfig, layer_idx: Optional[int] = None, use_tau: bool = True):
152
+ super().__init__()
153
+ self.config = config
154
+ self.layer_idx = layer_idx
155
+ self.hidden_size = config.hidden_size
156
+ self.num_heads = config.num_attention_heads
157
+ self.head_dim = getattr(config, "head_dim", self.hidden_size // self.num_heads)
158
+ self.num_key_value_heads = getattr(config, "num_key_value_heads", self.num_heads)
159
+ attention_bias = config.attention_bias
160
+ self.attention_dropout = config.attention_dropout
161
+
162
+ # Initialize parameters based on config type
163
+ if isinstance(config, Moondream3TextConfig):
164
+ self.is_causal = True
165
+ elif isinstance(config, Moondream3VisionConfig): # Moondream3VisionConfig
166
+ self.is_causal = False
167
+ else:
168
+ raise TypeError(f"Unsupported config type: {type(config)}")
169
+
170
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
171
+ self.use_tau = use_tau
172
+
173
+ if (self.head_dim * self.num_heads) != self.hidden_size:
174
+ raise ValueError(
175
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
176
+ f" and `num_heads`: {self.num_heads})."
177
+ )
178
+
179
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=attention_bias)
180
+ self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=attention_bias)
181
+ self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=attention_bias)
182
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=attention_bias)
183
+
184
+ # Tau parameters for token-level attention (from original Moondream) - only for text model
185
+ if self.use_tau:
186
+ # In original, tau weights are (n_heads, qkv_dim) where qkv_dim is the combined QKV dimension
187
+ qkv_dim = self.num_heads * self.head_dim + 2 * self.num_key_value_heads * self.head_dim
188
+ self.tau_wq = nn.Linear(qkv_dim, self.num_heads, bias=False)
189
+ self.tau_wv = nn.Linear(qkv_dim, self.num_heads, bias=False)
190
+ self.tau_alpha = nn.Parameter(torch.empty(self.num_heads))
191
+
192
+ def forward(
193
+ self,
194
+ hidden_states: torch.Tensor,
195
+ position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None,
196
+ attention_mask: Optional[torch.Tensor] = None,
197
+ position_ids: Optional[torch.LongTensor] = None,
198
+ past_key_values: Optional[Cache] = None,
199
+ output_attentions: bool = False,
200
+ use_cache: bool = False,
201
+ cache_position: Optional[torch.LongTensor] = None,
202
+ **kwargs,
203
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Cache]]:
204
+ input_shape = hidden_states.shape[:-1]
205
+ bsz, q_len, _ = hidden_states.size()
206
+
207
+ # Get qkv combined for tau (before splitting)
208
+ query_states = self.q_proj(hidden_states)
209
+ key_states = self.k_proj(hidden_states)
210
+ value_states = self.v_proj(hidden_states)
211
+ if self.use_tau:
212
+ qkv_out = torch.cat([query_states, key_states, value_states], dim=-1)
213
+ tok_feat = F.gelu(qkv_out)
214
+ tok_q = torch.tanh(self.tau_wq(tok_feat)).permute(0, 2, 1) # (bsz, n_heads, seq_len)
215
+ tok_v = torch.tanh(self.tau_wv(tok_feat)).permute(0, 2, 1) # (bsz, n_heads, seq_len)
216
+
217
+ pos = position_ids.to(tok_q.dtype) + 1
218
+ alpha = self.tau_alpha.to(tok_q.dtype)
219
+ tau_pos = 1 + (torch.sigmoid(alpha[None, :, None] * pos[:, None, :].log()) - 0.5) # (n_heads, seq_len)
220
+ tau_q = (tok_q + tau_pos).unsqueeze(-1) # (bsz, n_heads, seq_len, 1)
221
+ tau_v = (tok_v + tau_pos).unsqueeze(-1) # (bsz, n_heads, seq_len, 1)
222
+
223
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
224
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
225
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
226
+
227
+
228
+ if self.use_tau:
229
+ query_states = query_states * tau_q
230
+
231
+ if self.num_key_value_groups > 1:
232
+ tau_v_repeated = tau_v.repeat(1, self.num_key_value_groups, 1, 1)[:, :self.num_key_value_heads, :, :]
233
+ else:
234
+ tau_v_repeated = tau_v
235
+ value_states = value_states * tau_v_repeated
236
+
237
+ cos, sin = None, None
238
+ if position_embeddings is not None:
239
+ cos, sin = position_embeddings
240
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
241
+
242
+ if past_key_values is not None:
243
+
244
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
245
+ key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx, cache_kwargs)
246
+
247
+ attn_output, attn_weights = ALL_ATTENTION_FUNCTIONS["sdpa"](
248
+ self,
249
+ query_states,
250
+ key_states,
251
+ value_states,
252
+ attention_mask,
253
+ dropout=0.0 if not self.training else self.attention_dropout,
254
+ )
255
+
256
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
257
+ attn_output = self.o_proj(attn_output)
258
+
259
+ return attn_output, attn_weights
260
+
261
+ class Moondream3MLP(nn.Module):
262
+ def __init__(self, hidden_size: int, intermediate_size: int, hidden_act: str = "gelu_pytorch_tanh", out_size: int | None = None, gated: bool = False, bias: bool = True):
263
+ super().__init__()
264
+ self.hidden_size = hidden_size
265
+ self.intermediate_size = intermediate_size
266
+ self.out_size = self.hidden_size if out_size is None else out_size
267
+ self.hidden_act = hidden_act
268
+ self.gated = gated
269
+ # Ungated MLP: up_proj and down_proj following HF conventions
270
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=bias)
271
+ self.down_proj = nn.Linear(self.intermediate_size, self.out_size, bias=bias)
272
+ self.gate_proj = None
273
+ if self.gated:
274
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=bias)
275
+ self.act_fn = ACT2FN[self.hidden_act]
276
+
277
+ def forward(self, x) -> torch.Tensor:
278
+ if self.gated:
279
+ h = self.act_fn(self.up_proj(x))
280
+ g = self.gate_proj(x)
281
+ x = h * (g + 1)
282
+ else:
283
+ x = self.act_fn(self.up_proj(x))
284
+ return self.down_proj(x)
285
+
286
+
287
+ class Moondream3SparseMoeBlock(nn.Module):
288
+ def __init__(self, config: Moondream3TextConfig):
289
+ super().__init__()
290
+ self.hidden_size = config.hidden_size
291
+ self.moe_intermediate_size = config.moe_intermediate_size
292
+ self.num_experts = config.num_experts
293
+ self.top_k = config.num_experts_per_tok
294
+
295
+ self.gate = nn.Linear(self.hidden_size, self.num_experts, bias=True)
296
+ self.experts = nn.ModuleList([Moondream3MLP(hidden_size=self.hidden_size, intermediate_size=self.moe_intermediate_size, hidden_act="gelu", gated=True, bias=False) for _ in range(self.num_experts)])
297
+
298
+ def forward(self, hidden_states: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
299
+ batch_size, sequence_length, hidden_dim = hidden_states.shape
300
+ hidden_states = hidden_states.view(-1, hidden_dim)
301
+ router_logits: torch.Tensor = self.gate(hidden_states)
302
+
303
+ routing_weights = F.softmax(router_logits, dim=1, dtype=torch.float32)
304
+ routing_weights, selected_experts = torch.topk(routing_weights, self.top_k, dim=-1)
305
+ routing_weights /= routing_weights.sum(dim=-1, keepdim=True)
306
+ routing_weights = routing_weights.to(hidden_states.dtype)
307
+
308
+ final_hidden_states = torch.zeros(
309
+ (batch_size * sequence_length, hidden_dim), dtype=hidden_states.dtype, device=hidden_states.device
310
+ )
311
+
312
+ expert_mask = torch.nn.functional.one_hot(selected_experts, num_classes=self.num_experts).permute(2, 1, 0)
313
+
314
+ for expert_idx in range(self.num_experts):
315
+ expert_layer = self.experts[expert_idx]
316
+ idx, top_x = torch.where(expert_mask[expert_idx])
317
+
318
+ if top_x.shape[0] == 0:
319
+ continue
320
+
321
+ current_state = hidden_states[None, top_x].reshape(-1, hidden_dim)
322
+ current_hidden_states = expert_layer(current_state) * routing_weights[top_x, idx, None]
323
+
324
+ final_hidden_states.index_add_(0, top_x, current_hidden_states.to(hidden_states.dtype))
325
+
326
+ final_hidden_states = final_hidden_states.reshape(batch_size, sequence_length, hidden_dim)
327
+ return final_hidden_states, router_logits
328
+
329
+
330
+ class Moondream3DecoderLayer(nn.Module):
331
+ def __init__(self, config: Moondream3TextConfig, layer_idx: int):
332
+ super().__init__()
333
+ self.hidden_size = config.hidden_size
334
+ self.intermediate_size = config.intermediate_size
335
+ self.self_attn = Moondream3Attention(config, layer_idx, use_tau=True)
336
+ self.input_layernorm = nn.LayerNorm(config.hidden_size, eps=config.rms_norm_eps)
337
+
338
+ self.is_moe_layer = layer_idx >= config.moe_start_layer
339
+ if self.is_moe_layer:
340
+ self.mlp = Moondream3SparseMoeBlock(config)
341
+ else:
342
+ self.mlp = Moondream3MLP(self.hidden_size, self.intermediate_size)
343
+
344
+ def forward(
345
+ self,
346
+ hidden_states: torch.Tensor,
347
+ attention_mask: Optional[torch.Tensor] = None,
348
+ position_ids: Optional[torch.LongTensor] = None,
349
+ past_key_values: Optional[Cache] = None,
350
+ output_attentions: bool = False,
351
+ output_router_logits: bool = False,
352
+ use_cache: bool = False,
353
+ cache_position: Optional[torch.LongTensor] = None,
354
+ position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None,
355
+ **kwargs,
356
+ ) -> Tuple:
357
+ residual = hidden_states
358
+
359
+ # Apply layer norm like original
360
+ l_in = self.input_layernorm(hidden_states)
361
+
362
+ # Attention
363
+ hidden_states_attn, self_attn_weights = self.self_attn(
364
+ hidden_states=l_in,
365
+ attention_mask=attention_mask,
366
+ position_ids=position_ids,
367
+ past_key_values=past_key_values,
368
+ output_attentions=output_attentions,
369
+ use_cache=use_cache,
370
+ cache_position=cache_position,
371
+ position_embeddings=position_embeddings,
372
+ **kwargs
373
+ )
374
+
375
+ # MLP
376
+ if self.is_moe_layer:
377
+ hidden_states_mlp, router_logits = self.mlp(l_in)
378
+ else:
379
+ hidden_states_mlp = self.mlp(l_in)
380
+ router_logits = None
381
+
382
+ # Add both attention and MLP to residual like original
383
+ hidden_states = residual + hidden_states_attn + hidden_states_mlp
384
+
385
+ outputs = (hidden_states,)
386
+
387
+ if output_attentions:
388
+ outputs += (self_attn_weights,)
389
+
390
+ if output_router_logits:
391
+ outputs += (router_logits,)
392
+
393
+ return outputs
394
+
395
+
396
+ class Moondream3PreTrainedModel(PreTrainedModel):
397
+ config_class = Moondream3Config
398
+ base_model_prefix = "model"
399
+ supports_gradient_checkpointing = True
400
+ _no_split_modules = ["Moondream3DecoderLayer", "Moondream3SparseMoeBlock"]
401
+ _skip_keys_device_placement = "past_key_values"
402
+ _supports_flash_attn_2 = True
403
+ _supports_sdpa = True
404
+ _supports_cache_class = True
405
+
406
+ def _init_weights(self, module):
407
+ # Use text_config initializer_range if available, otherwise use default
408
+ if hasattr(self.config, 'text_config') and hasattr(self.config.text_config, 'initializer_range'):
409
+ std = self.config.text_config.initializer_range
410
+ elif hasattr(self.config, 'initializer_range'):
411
+ std = self.config.initializer_range
412
+ else:
413
+ std = 0.02 # Default initialization range
414
+
415
+ if isinstance(module, nn.Linear):
416
+ module.weight.data.normal_(mean=0.0, std=std)
417
+ if module.bias is not None:
418
+ module.bias.data.zero_()
419
+ elif isinstance(module, nn.Embedding):
420
+ module.weight.data.normal_(mean=0.0, std=std)
421
+ if module.padding_idx is not None:
422
+ module.weight.data[module.padding_idx].zero_()
423
+
424
+
425
+ class Moondream3TextModel(Moondream3PreTrainedModel):
426
+ config_class = Moondream3TextConfig
427
+
428
+ def __init__(self, config: Moondream3TextConfig):
429
+ super().__init__(config)
430
+ self.padding_idx = config.pad_token_id if hasattr(config, "pad_token_id") else 0
431
+ self.vocab_size = config.vocab_size
432
+
433
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
434
+ self.layers = nn.ModuleList(
435
+ [Moondream3DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
436
+ )
437
+ self.norm = nn.LayerNorm(config.hidden_size, eps=config.rms_norm_eps)
438
+ self.rotary_emb = Moondream3RotaryEmbedding(config=config)
439
+ self.gradient_checkpointing = False
440
+
441
+
442
+ self.post_init()
443
+
444
+ def forward(
445
+ self,
446
+ input_ids: Optional[torch.LongTensor] = None,
447
+ attention_mask: Optional[torch.Tensor] = None,
448
+ position_ids: Optional[torch.LongTensor] = None,
449
+ past_key_values: Optional[Cache] = None,
450
+ inputs_embeds: Optional[torch.FloatTensor] = None,
451
+ use_cache: Optional[bool] = None,
452
+ output_attentions: Optional[bool] = None,
453
+ output_hidden_states: Optional[bool] = None,
454
+ output_router_logits: Optional[bool] = None,
455
+ return_dict: Optional[bool] = None,
456
+ cache_position: Optional[torch.LongTensor] = None,
457
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
458
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
459
+ output_router_logits = (
460
+ output_router_logits if output_router_logits is not None else self.config.output_router_logits
461
+ )
462
+ output_hidden_states = (
463
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
464
+ )
465
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
466
+
467
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
468
+
469
+ if (input_ids is None) ^ (inputs_embeds is not None):
470
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time, and must specify either one")
471
+
472
+ if inputs_embeds is None:
473
+ inputs_embeds = self.embed_tokens(input_ids)
474
+
475
+ hidden_states = inputs_embeds
476
+ batch_size = hidden_states.shape[0]
477
+
478
+ if self.gradient_checkpointing and self.training:
479
+ if use_cache:
480
+ logger.warning(
481
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
482
+ )
483
+ use_cache = False
484
+
485
+ if use_cache and past_key_values is None:
486
+ past_key_values = DynamicCache()
487
+
488
+ if cache_position is None:
489
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
490
+ cache_position = torch.arange(
491
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
492
+ )
493
+
494
+ if position_ids is None:
495
+ position_ids = cache_position.unsqueeze(0)
496
+
497
+ position_embeddings = self.rotary_emb(hidden_states, position_ids=position_ids)
498
+
499
+ all_hidden_states = () if output_hidden_states else None
500
+ all_self_attns = () if output_attentions else None
501
+ all_router_logits = () if output_router_logits else None
502
+
503
+ for decoder_layer in self.layers:
504
+ if output_hidden_states:
505
+ all_hidden_states += (hidden_states,)
506
+
507
+ if self.gradient_checkpointing and self.training:
508
+ layer_outputs = self._gradient_checkpointing_func(
509
+ decoder_layer.__call__,
510
+ hidden_states,
511
+ attention_mask,
512
+ position_ids,
513
+ past_key_values,
514
+ output_attentions,
515
+ output_router_logits,
516
+ use_cache,
517
+ cache_position,
518
+ position_embeddings
519
+ )
520
+ else:
521
+ layer_outputs = decoder_layer(
522
+ hidden_states,
523
+ attention_mask=attention_mask,
524
+ position_ids=position_ids,
525
+ past_key_values=past_key_values,
526
+ output_attentions=output_attentions,
527
+ output_router_logits=output_router_logits,
528
+ use_cache=use_cache,
529
+ cache_position=cache_position,
530
+ position_embeddings=position_embeddings
531
+ )
532
+
533
+ hidden_states = layer_outputs[0]
534
+
535
+ if output_attentions:
536
+ all_self_attns += (layer_outputs[1],)
537
+
538
+ if output_router_logits and layer_outputs[-1] is not None:
539
+ all_router_logits += (layer_outputs[-1],)
540
+
541
+ hidden_states = self.norm(hidden_states)
542
+
543
+ if output_hidden_states:
544
+ all_hidden_states += (hidden_states,)
545
+
546
+ next_cache = None
547
+ if use_cache:
548
+ next_cache = past_key_values
549
+
550
+ if not return_dict:
551
+ return tuple(
552
+ v
553
+ for v in [hidden_states, next_cache, all_hidden_states, all_self_attns, all_router_logits]
554
+ if v is not None
555
+ )
556
+
557
+ return BaseModelOutputWithPast(
558
+ last_hidden_state=hidden_states,
559
+ past_key_values=next_cache,
560
+ hidden_states=all_hidden_states,
561
+ attentions=all_self_attns,
562
+ )
563
+
564
+
565
+ class Moondream3VisionPatchEmbeddings(nn.Module):
566
+ def __init__(self, config: Moondream3VisionConfig):
567
+ super().__init__()
568
+ self.patch_size = config.patch_size
569
+ self.num_channels = config.in_channels
570
+ self.hidden_size = config.hidden_size
571
+ self.crop_size = config.crop_size
572
+ self.patch_size = config.patch_size
573
+ self.grid_size = self.crop_size // self.patch_size
574
+ self.num_patches = self.grid_size * self.grid_size
575
+
576
+ self.projection = nn.Linear(self.patch_size * self.patch_size * self.num_channels, self.hidden_size, bias=True)
577
+ self.position_embeddings = nn.Parameter(torch.zeros(1, self.num_patches, config.hidden_size))
578
+
579
+ def forward(self, pixel_values: torch.Tensor) -> torch.Tensor:
580
+ B, C, H, W = pixel_values.shape
581
+ P1 = P2 = self.patch_size
582
+
583
+ x = pixel_values.reshape(B, C, H // P1, P1, W // P2, P2)
584
+
585
+ x = x.permute(0, 2, 4, 1, 3, 5)
586
+
587
+ x = x.reshape(B, (H // P1) * (W // P2), C * P1 * P2)
588
+
589
+ x = self.projection(x)
590
+ return x + self.position_embeddings
591
+
592
+ class Moondream3VisionEncoderLayer(nn.Module):
593
+ def __init__(self, config: Moondream3VisionConfig, layer_idx: int):
594
+ super().__init__()
595
+ self.hidden_size = config.hidden_size
596
+ self.intermediate_size = config.intermediate_size
597
+ self.layer_idx = layer_idx
598
+
599
+ self.self_attn = Moondream3Attention(config, layer_idx=self.layer_idx, use_tau=False)
600
+ self.input_layernorm = nn.LayerNorm(config.hidden_size, eps=1e-5)
601
+ self.post_attention_layernorm = nn.LayerNorm(config.hidden_size, eps=1e-5)
602
+ self.mlp = Moondream3MLP(hidden_size=self.hidden_size, intermediate_size=self.intermediate_size)
603
+
604
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
605
+ residual = hidden_states
606
+ hidden_states = self.input_layernorm(hidden_states)
607
+ hidden_states, _ = self.self_attn(hidden_states=hidden_states)
608
+ hidden_states = residual + hidden_states
609
+
610
+ residual = hidden_states
611
+ hidden_states = self.post_attention_layernorm(hidden_states)
612
+ hidden_states = self.mlp(hidden_states)
613
+ hidden_states = residual + hidden_states
614
+
615
+ return hidden_states
616
+
617
+ class Moondream3VisionModel(Moondream3PreTrainedModel):
618
+ config_class = Moondream3VisionConfig
619
+ main_input_name = "pixel_values"
620
+ _no_split_modules = ["Moondream3VisionEncoderLayer"]
621
+
622
+ def __init__(self, config: Moondream3VisionConfig):
623
+ super().__init__(config)
624
+ self.config = config
625
+ self.hidden_size = self.config.hidden_size
626
+ self.num_hidden_layers = self.config.num_hidden_layers
627
+ self.proj_inner_dim = self.config.proj_inner_dim
628
+ self.proj_out_dim = self.config.proj_out_dim
629
+
630
+ self.embeddings = Moondream3VisionPatchEmbeddings(config)
631
+ self.layers = nn.ModuleList([Moondream3VisionEncoderLayer(config,layer_idx) for layer_idx in range(self.num_hidden_layers)])
632
+ self.post_layernorm = nn.LayerNorm(self.hidden_size, eps=1e-5)
633
+ self.vision_projection = Moondream3MLP(hidden_size=self.hidden_size * 2, intermediate_size=self.proj_inner_dim, out_size=self.proj_out_dim)
634
+ self.gradient_checkpointing = False
635
+ self.post_init()
636
+
637
+ def _reconstruct_from_crops(
638
+ self,
639
+ crops: torch.Tensor,
640
+ tiling: tuple[int, int],
641
+ overlap_margin: int = 4,
642
+ patch_size: int = 14,
643
+ ) -> torch.Tensor:
644
+ """
645
+ Reconstruct the original image from overlapping crops into a single seamless image.
646
+
647
+ Takes a list of overlapping image crops along with their positional metadata and
648
+ reconstructs them into a single coherent image by carefully stitching together
649
+ non-overlapping regions. Handles both numpy arrays and PyTorch tensors.
650
+
651
+ Args:
652
+ crops: List of image crops as numpy arrays or PyTorch tensors with shape
653
+ (H,W,C)
654
+ tiling: Tuple of (height,width) indicating crop grid layout
655
+ patch_size: Size in pixels of each patch, default 14
656
+ overlap_margin: Number of overlapping patches on each edge, default 4
657
+
658
+ Returns:
659
+ Reconstructed image as numpy array or PyTorch tensor matching input type,
660
+ with shape (H,W,C) where H,W are the original image dimensions
661
+ """
662
+ if isinstance(tiling, torch.Tensor):
663
+ tiling_h, tiling_w = tiling[0].item(), tiling[1].item()
664
+ else:
665
+ tiling_h, tiling_w = tiling
666
+ tiling_h, tiling_w = int(tiling_h), int(tiling_w)
667
+ crop_height, crop_width = crops[0].shape[:2]
668
+ margin_pixels = overlap_margin * patch_size
669
+
670
+ # Calculate output size (only adding margins once)
671
+ output_h = (crop_height - 2 * margin_pixels) * tiling_h + 2 * margin_pixels
672
+ output_w = (crop_width - 2 * margin_pixels) * tiling_w + 2 * margin_pixels
673
+ reconstructed = torch.zeros(
674
+ (output_h, output_w, crops[0].shape[2]),
675
+ device=crops[0].device,
676
+ dtype=crops[0].dtype,
677
+ )
678
+
679
+ for i, crop in enumerate(crops):
680
+ tile_y = i // tiling_w
681
+ tile_x = i % tiling_w
682
+
683
+ # For each tile, determine which part to keep
684
+ # Keep left margin only for first column
685
+ x_start = 0 if tile_x == 0 else margin_pixels
686
+ # Keep right margin only for last column
687
+ x_end = crop_width if tile_x == tiling_w - 1 else crop_width - margin_pixels
688
+ # Keep top margin only for first row
689
+ y_start = 0 if tile_y == 0 else margin_pixels
690
+ # Keep bottom margin only for last row
691
+ y_end = crop_height if tile_y == tiling_h - 1 else crop_height - margin_pixels
692
+
693
+ # Calculate where this piece belongs in the output
694
+ out_x = tile_x * (crop_width - 2 * margin_pixels)
695
+ out_y = tile_y * (crop_height - 2 * margin_pixels)
696
+
697
+ # Place the piece
698
+ reconstructed[
699
+ out_y + y_start : out_y + y_end, out_x + x_start : out_x + x_end
700
+ ] = crop[y_start:y_end, x_start:x_end]
701
+
702
+ return reconstructed
703
+
704
+ def forward(
705
+ self,
706
+ pixel_values: torch.FloatTensor,
707
+ tiling: Tuple[int,int],
708
+ output_attentions: Optional[bool] = None,
709
+ output_hidden_states: Optional[bool] = None,
710
+ return_dict: Optional[bool] = None,
711
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
712
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
713
+ output_hidden_states = (
714
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
715
+ )
716
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
717
+
718
+ batch_size, num_crops = pixel_values.shape[:2]
719
+ # flatten batch_size and num_crops into same dim
720
+ pixel_values = pixel_values.view(-1, *pixel_values.shape[2:])
721
+ hidden_states: torch.Tensor = self.embeddings(pixel_values)
722
+
723
+ all_hidden_states = () if output_hidden_states else None
724
+ all_attentions = () if output_attentions else None
725
+
726
+ for encoder_layer in self.layers:
727
+ if output_hidden_states and all_hidden_states is not None:
728
+ all_hidden_states += (hidden_states,)
729
+
730
+ if self.gradient_checkpointing and self.training:
731
+ layer_outputs = self._gradient_checkpointing_func(encoder_layer.__call__, hidden_states)
732
+ else:
733
+ layer_outputs = encoder_layer(hidden_states)
734
+
735
+ hidden_states = layer_outputs
736
+
737
+ hidden_states = self.post_layernorm(hidden_states)
738
+ # B, _, _
739
+
740
+ # back out into batch_size, num_crops
741
+ hidden_states = hidden_states.view(batch_size, num_crops, *hidden_states.shape[1:])
742
+ outputs = []
743
+ for b in range(batch_size):
744
+ hs = hidden_states[b]
745
+ t = tiling[b]
746
+
747
+ global_features = hs[0]
748
+ local_features = hs[1:].view(
749
+ -1,
750
+ self.num_hidden_layers,
751
+ self.num_hidden_layers,
752
+ self.hidden_size,
753
+ )
754
+
755
+ reconstructed = self._reconstruct_from_crops(
756
+ local_features,
757
+ t,
758
+ patch_size=1,
759
+ overlap_margin=self.config.overlap_margin,
760
+ )
761
+
762
+ reconstructed = reconstructed.permute(2, 0, 1)
763
+ reconstructed = F.adaptive_avg_pool2d(
764
+ reconstructed, output_size=(self.num_hidden_layers, self.num_hidden_layers)
765
+ )
766
+ reconstructed = reconstructed.permute(1, 2, 0).view(729, self.hidden_size)
767
+ final_features = torch.cat([global_features, reconstructed], dim=-1)
768
+ outputs.append(final_features)
769
+ output = torch.stack(outputs, 0)
770
+
771
+ hidden_states = self.vision_projection(output)
772
+
773
+ if output_hidden_states and all_hidden_states is not None:
774
+ all_hidden_states += (hidden_states,)
775
+
776
+ if not return_dict:
777
+ return tuple(v for v in [hidden_states, all_hidden_states, all_attentions] if v is not None)
778
+
779
+ return BaseModelOutputWithPast(
780
+ last_hidden_state=hidden_states,
781
+ hidden_states=all_hidden_states,
782
+ attentions=all_attentions,
783
+ )
784
+
785
+ class Moondream3RegionEncoder(nn.Module):
786
+ def __init__(self, config: Moondream3RegionConfig):
787
+ super().__init__()
788
+ self.coord_encoder = nn.Linear(config.coord_feat_dim, config.hidden_size)
789
+ self.size_encoder = nn.Linear(config.size_feat_dim, config.hidden_size)
790
+
791
+ coord_freq = torch.randn(config.coord_feat_dim // 2, 1) * 10.0
792
+ size_freq = torch.randn(config.size_feat_dim // 2, 2) * 10.0
793
+ self.register_buffer("coord_freq", coord_freq.T)
794
+ self.register_buffer("size_freq", size_freq.T)
795
+
796
+ def fourier_features(self, x: torch.Tensor, w: torch.Tensor) -> torch.Tensor:
797
+ x_proj = torch.matmul(x, w) * 2 * torch.pi
798
+ return torch.cat([torch.sin(x_proj), torch.cos(x_proj)], dim=-1)
799
+
800
+ def encode_coordinate(self, coord: torch.Tensor) -> torch.Tensor:
801
+ fourier_features = self.fourier_features(coord, self.coord_freq)
802
+ return self.coord_encoder(fourier_features)
803
+
804
+ def encode_size(self, size: torch.Tensor) -> torch.Tensor:
805
+ fourier_features = self.fourier_features(size, self.size_freq)
806
+ return self.size_encoder(fourier_features)
807
+
808
+ class Moondream3RegionDecoder(nn.Module):
809
+ def __init__(self, config: Moondream3RegionConfig):
810
+ super().__init__()
811
+ self.coord_decoder = nn.Linear(config.hidden_size, config.coord_out_dim)
812
+ self.size_decoder = nn.Linear(config.hidden_size, config.size_out_dim)
813
+
814
+ def decode_coordinate(self, hidden_state: torch.Tensor) -> torch.Tensor:
815
+ return self.coord_decoder(hidden_state)
816
+
817
+ def decode_size(self, hidden_state: torch.Tensor) -> torch.Tensor:
818
+ return self.size_decoder(hidden_state)
819
+
820
+ class Moondream3Model(Moondream3PreTrainedModel):
821
+ def __init__(self, config: Moondream3Config):
822
+ super().__init__(config)
823
+ self.text_model = Moondream3TextModel(config.text_config)
824
+ self.vision_model = Moondream3VisionModel(config.vision_config)
825
+ self.vocab_size = config.text_config.vocab_size
826
+
827
+ self.region_encoder = Moondream3RegionEncoder(config.region_config)
828
+ self.region_decoder = Moondream3RegionDecoder(config.region_config)
829
+ self.post_init()
830
+
831
+ def get_input_embeddings(self):
832
+ return self.text_model.embed_tokens
833
+
834
+ def set_input_embeddings(self, value):
835
+ self.text_model.embed_tokens = value
836
+
837
+ def set_decoder(self, decoder):
838
+ self.text_model = decoder
839
+
840
+ def get_decoder(self):
841
+ return self.text_model
842
+
843
+ def forward(
844
+ self,
845
+ input_ids: torch.LongTensor = None,
846
+ pixel_values: torch.FloatTensor = None,
847
+ tiling: Tuple[int,int] = None,
848
+ attention_mask: Optional[torch.Tensor] = None,
849
+ position_ids: Optional[torch.LongTensor] = None,
850
+ past_key_values: Optional[Cache] = None,
851
+ inputs_embeds: Optional[torch.FloatTensor] = None,
852
+ labels: Optional[torch.LongTensor] = None,
853
+ use_cache: Optional[bool] = None,
854
+ output_attentions: Optional[bool] = None,
855
+ output_hidden_states: Optional[bool] = None,
856
+ return_dict: Optional[bool] = None,
857
+ cache_position: Optional[torch.LongTensor] = None,
858
+ logits_to_keep: int = 0,
859
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
860
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
861
+ output_hidden_states = (
862
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
863
+ )
864
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
865
+
866
+ if (input_ids is not None) == (inputs_embeds is not None):
867
+ raise ValueError("Provide exactly one of input_ids or inputs_embeds.")
868
+
869
+ if not ((pixel_values is not None) ^ (tiling is None)):
870
+ raise ValueError("You must specify both pixel_values and tiling")
871
+
872
+ # Case A: inputs_embeds provided -> assume it already contains BOS+image+text in correct order.
873
+ if inputs_embeds is not None and (pixel_values is not None or tiling is not None):
874
+ raise ValueError(
875
+ "When inputs_embeds is provided, do not pass pixel_values/tiling; "
876
+ "inputs_embeds must already include BOS+image(+text)."
877
+ )
878
+
879
+ if inputs_embeds is None:
880
+ inputs_embeds: torch.Tensor = self.text_model.embed_tokens(input_ids)
881
+
882
+ if use_cache and past_key_values is None:
883
+ past_key_values = DynamicCache(config=self.config)
884
+
885
+ if cache_position is None:
886
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
887
+ cache_position: torch.Tensor = torch.arange(
888
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
889
+ )
890
+
891
+ if position_ids is None:
892
+ position_ids = cache_position.unsqueeze(0)
893
+
894
+ causal_mask = create_causal_mask(
895
+ config=self.config,
896
+ input_embeds=inputs_embeds,
897
+ attention_mask=attention_mask,
898
+ cache_position=cache_position,
899
+ past_key_values=past_key_values,
900
+ position_ids=position_ids,
901
+ )
902
+
903
+ if pixel_values is not None and input_ids.shape[-1] > 1:
904
+ # Vision embeds
905
+ pixel_values = pixel_values.to(dtype=self.vision_model.embeddings.projection.weight.dtype)
906
+ image_embeds = self.vision_model(pixel_values, tiling=tiling)["last_hidden_state"] # [B,P,D]
907
+ prefix = inputs_embeds[:, :1, :] # keep the first token
908
+ suffix = inputs_embeds[:, 1 + image_embeds.shape[1] :, :] # keep the rest after the image span
909
+ inputs_embeds = torch.cat([prefix, image_embeds, suffix], dim=1)
910
+
911
+ # N/A when doing BSZ 1 since create_causal_mask returns None in the case since theres no padding tokens
912
+ if causal_mask is not None:
913
+ img_len = image_embeds.shape[1]
914
+ causal_mask[:, :, :1 + img_len, :1 + img_len] = True
915
+ causal_mask[:, :, :1 + img_len, 1 + img_len:] = False
916
+
917
+ outputs = self.text_model(
918
+ input_ids=None,
919
+ attention_mask=causal_mask,
920
+ position_ids=position_ids,
921
+ past_key_values=past_key_values,
922
+ inputs_embeds=inputs_embeds,
923
+ use_cache=use_cache,
924
+ output_attentions=output_attentions,
925
+ output_hidden_states=output_hidden_states,
926
+ return_dict=True,
927
+ cache_position=cache_position,
928
+ )
929
+
930
+ if not return_dict:
931
+ return tuple(v for v in [
932
+ outputs.last_hidden_state,
933
+ getattr(outputs, "past_key_values", None),
934
+ getattr(outputs, "hidden_states", None),
935
+ getattr(outputs, "attentions", None),
936
+ ] if v is not None)
937
+
938
+ return BaseModelOutputWithPast(
939
+ last_hidden_state=outputs.last_hidden_state,
940
+ past_key_values=getattr(outputs, "past_key_values", None),
941
+ hidden_states=getattr(outputs, "hidden_states", None),
942
+ attentions=getattr(outputs, "attentions", None),
943
+ )
944
+
945
+ class Moondream3ForConditionalGeneration(Moondream3PreTrainedModel, GenerationMixin):
946
+ _tied_weights_keys = ["lm_head.weight"]
947
+
948
+ def __init__(self, config: Moondream3Config):
949
+ super().__init__(config)
950
+ self.model = Moondream3Model(config)
951
+ self.vocab_size = config.text_config.vocab_size
952
+ self.lm_head = nn.Linear(config.text_config.hidden_size, config.text_config.vocab_size, bias=True)
953
+ self.post_init()
954
+
955
+ def get_input_embeddings(self):
956
+ return self.model.text_model.embed_tokens
957
+
958
+ def set_input_embeddings(self, value):
959
+ self.model.text_model.embed_tokens = value
960
+
961
+ def get_output_embeddings(self):
962
+ return self.lm_head
963
+
964
+ def set_output_embeddings(self, new_embeddings):
965
+ self.lm_head = new_embeddings
966
+
967
+ def set_decoder(self, decoder):
968
+ self.model.text_model = decoder
969
+
970
+ def get_decoder(self):
971
+ return self.model.text_model
972
+
973
+ def forward(
974
+ self,
975
+ input_ids: torch.LongTensor = None,
976
+ pixel_values: torch.FloatTensor = None,
977
+ tiling: torch.LongTensor = None,
978
+ attention_mask: Optional[torch.Tensor] = None,
979
+ position_ids: Optional[torch.LongTensor] = None,
980
+ past_key_values: Optional[Cache] = None,
981
+ inputs_embeds: Optional[torch.FloatTensor] = None,
982
+ labels: Optional[torch.LongTensor] = None,
983
+ use_cache: Optional[bool] = None,
984
+ output_attentions: Optional[bool] = None,
985
+ output_hidden_states: Optional[bool] = None,
986
+ return_dict: Optional[bool] = None,
987
+ cache_position: Optional[torch.LongTensor] = None,
988
+ logits_to_keep: int = 0,
989
+ **kwargs: Unpack[TransformersKwargs],
990
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
991
+ # Get hidden states from the base model (it already builds the multimodal prefix)
992
+ model_outputs = self.model(
993
+ input_ids=input_ids,
994
+ pixel_values=pixel_values,
995
+ tiling=tiling,
996
+ attention_mask=attention_mask,
997
+ position_ids=position_ids,
998
+ past_key_values=past_key_values,
999
+ inputs_embeds=inputs_embeds,
1000
+ labels=None,
1001
+ use_cache=use_cache,
1002
+ output_attentions=output_attentions,
1003
+ output_hidden_states=output_hidden_states,
1004
+ return_dict=True,
1005
+ cache_position=cache_position,
1006
+ logits_to_keep=logits_to_keep,
1007
+ )
1008
+
1009
+ hidden_states = model_outputs.last_hidden_state # [B, T, D]
1010
+
1011
+ # Compute logits; only keep the tail if requested
1012
+ if isinstance(logits_to_keep, int) and logits_to_keep > 0:
1013
+ hs = hidden_states[:, -logits_to_keep:, :]
1014
+ elif isinstance(logits_to_keep, slice):
1015
+ hs = hidden_states[:, logits_to_keep, :]
1016
+ else:
1017
+ hs = hidden_states
1018
+
1019
+ logits = self.lm_head(hs) # [B, T', V]
1020
+
1021
+ loss = None
1022
+ if labels is not None:
1023
+ # Shift if your training uses standard LM convention; here we assume labels aligned with hs
1024
+ loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.vocab_size)
1025
+
1026
+ return CausalLMOutputWithPast(
1027
+ loss=loss,
1028
+ logits=logits,
1029
+ past_key_values=getattr(model_outputs, "past_key_values", None),
1030
+ hidden_states=getattr(model_outputs, "hidden_states", None),
1031
+ attentions=getattr(model_outputs, "attentions", None),
1032
+ )
1033
+
1034
+ @staticmethod
1035
+ def _reorder_cache(past_key_values, beam_idx):
1036
+ reordered_past = ()
1037
+ for layer_past in past_key_values:
1038
+ reordered_past += (
1039
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1040
+ )
1041
+ return reordered_past
1042
+
1043
+
1044
+ __all__ = [
1045
+ "Moondream3Config",
1046
+ "Moondream3TextConfig",
1047
+ "Moondream3VisionConfig",
1048
+ "Moondream3RegionConfig",
1049
+ "Moondream3PreTrainedModel",
1050
+ "Moondream3Model",
1051
+ "Moondream3TextModel",
1052
+ "Moondream3VisionModel",
1053
+ "Moondream3ForConditionalGeneration",
1054
+ ]
modeling_moondream3_fusedmoe.py ADDED
@@ -0,0 +1,301 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2025 The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ from typing import Callable, Optional, Tuple, Union
17
+
18
+ import numpy as np
19
+ import math
20
+ import torch
21
+ import torch.nn as nn
22
+ import torch.nn.functional as F
23
+
24
+ from PIL import Image
25
+
26
+ from transformers.activations import ACT2FN
27
+ from transformers.cache_utils import Cache, DynamicCache
28
+ from transformers.masking_utils import create_causal_mask
29
+ from transformers.modeling_outputs import (
30
+ BaseModelOutputWithPast,
31
+ CausalLMOutputWithPast,
32
+ )
33
+ from transformers.processing_utils import Unpack
34
+ from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
35
+ from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel, load_state_dict
36
+ from transformers.generation import GenerationMixin
37
+ from transformers.utils import logging, TransformersKwargs
38
+
39
+ from .moondream3_moe_fused.moe_fused_linear import MoeFusedLinear
40
+ from .moondream3_moe_fused.kernels.indexing import get_expert_counts_and_idx
41
+ from .configuration_moondream3 import Moondream3Config, Moondream3TextConfig, Moondream3VisionConfig, Moondream3RegionConfig
42
+
43
+ from . import modeling_moondream3
44
+
45
+ logger = logging.get_logger(__name__)
46
+
47
+ _CONFIG_FOR_DOC = "Moondream3Config"
48
+
49
+ class Moondream3FusedSparseMoeBlock(nn.Module):
50
+ def __init__(self, config: Moondream3TextConfig) -> None:
51
+ super().__init__()
52
+ self.num_experts = config.num_experts
53
+ self.num_selected = config.num_experts_per_tok
54
+ self.hidden_size = config.hidden_size
55
+ self.moe_intermediate_size = config.moe_intermediate_size
56
+
57
+ self.gate = nn.Linear(config.hidden_size, config.num_experts, bias=False)
58
+ self.gate_proj = MoeFusedLinear(self.hidden_size, self.moe_intermediate_size, config.num_experts)
59
+ self.up_proj = MoeFusedLinear(self.hidden_size, self.moe_intermediate_size, config.num_experts)
60
+ self.down_proj = MoeFusedLinear(self.moe_intermediate_size, self.hidden_size, config.num_experts)
61
+
62
+ def forward(self, hidden_states: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
63
+ batch_size, sequence_length, hidden_dim = hidden_states.shape
64
+ M = batch_size * sequence_length
65
+
66
+ hidden_states = hidden_states.view(M, hidden_dim)
67
+ # router_logits: (M, num_experts)
68
+ router_logits = self.gate(hidden_states)
69
+
70
+ routing_weights = F.softmax(router_logits, dim=1, dtype=torch.float32)
71
+ # routing_weights, selected_experts: (M, num_selected)
72
+ routing_weights, selected_experts = torch.topk(routing_weights, self.num_selected, dim=-1)
73
+ routing_weights /= routing_weights.sum(dim=-1, keepdim=True)
74
+ # we cast back to the input dtype
75
+ routing_weights = routing_weights.to(hidden_states.dtype)
76
+
77
+ hidden_states = hidden_states.unsqueeze(1).expand(M, self.num_selected, hidden_dim)
78
+ # hidden_states must be contiguous
79
+ hidden_states = hidden_states.reshape(M * self.num_selected, hidden_dim)
80
+ selected_experts = selected_experts.view(M * self.num_selected)
81
+
82
+ # Sort selected_experts and hidden_states for better memory coalescence of weight
83
+ # It's possible to fuse a sort and a MoeFusedLinear layer, but for now we separate them for clarity
84
+ m_sizes, sort_idx, inv_sort_idx = get_expert_counts_and_idx(selected_experts, self.num_experts)
85
+ hidden_states = hidden_states[sort_idx]
86
+
87
+ # It's possible to fuse gate_h and up_h, but this affects the shape of LoRA
88
+ gate_h = self.gate_proj(hidden_states, m_sizes)
89
+ up_h = self.up_proj(hidden_states, m_sizes)
90
+ hidden_states = F.gelu(up_h) * (gate_h + 1)
91
+ del gate_h, up_h
92
+ hidden_states = self.down_proj(hidden_states, m_sizes)
93
+
94
+ hidden_states = hidden_states[inv_sort_idx]
95
+
96
+ hidden_states = hidden_states.view(M, self.num_selected, hidden_dim)
97
+ hidden_states = torch.einsum("beo,be->bo", hidden_states, routing_weights)
98
+
99
+ hidden_states = hidden_states.view(batch_size, sequence_length, hidden_dim)
100
+ return hidden_states, router_logits
101
+
102
+ modeling_moondream3.Moondream3SparseMoeBlock = Moondream3FusedSparseMoeBlock
103
+ from .modeling_moondream3 import Moondream3Config, Moondream3TextConfig, Moondream3VisionConfig, Moondream3RegionConfig, Moondream3PreTrainedModel, Moondream3Model, Moondream3TextModel, Moondream3VisionModel, Moondream3ForConditionalGeneration
104
+
105
+
106
+ class Moondream3ForConditionalGeneration(Moondream3PreTrainedModel, GenerationMixin):
107
+ _tied_weights_keys = ["lm_head.weight"]
108
+
109
+ def __init__(self, config: Moondream3Config):
110
+ super().__init__(config)
111
+ self.model = Moondream3Model(config)
112
+ self.vocab_size = config.text_config.vocab_size
113
+ self.lm_head = nn.Linear(config.text_config.hidden_size, config.text_config.vocab_size, bias=True)
114
+ self.post_init()
115
+
116
+ def get_input_embeddings(self):
117
+ return self.model.text_model.embed_tokens
118
+
119
+ def set_input_embeddings(self, value):
120
+ self.model.text_model.embed_tokens = value
121
+
122
+ def get_output_embeddings(self):
123
+ return self.lm_head
124
+
125
+ def set_output_embeddings(self, new_embeddings):
126
+ self.lm_head = new_embeddings
127
+
128
+ def set_decoder(self, decoder):
129
+ self.model.text_model = decoder
130
+
131
+ def get_decoder(self):
132
+ return self.model.text_model
133
+
134
+ def forward(
135
+ self,
136
+ input_ids: torch.LongTensor = None,
137
+ pixel_values: torch.FloatTensor = None,
138
+ tiling: torch.LongTensor = None,
139
+ attention_mask: Optional[torch.Tensor] = None,
140
+ position_ids: Optional[torch.LongTensor] = None,
141
+ past_key_values: Optional[Cache] = None,
142
+ inputs_embeds: Optional[torch.FloatTensor] = None,
143
+ labels: Optional[torch.LongTensor] = None,
144
+ use_cache: Optional[bool] = None,
145
+ output_attentions: Optional[bool] = None,
146
+ output_hidden_states: Optional[bool] = None,
147
+ return_dict: Optional[bool] = None,
148
+ cache_position: Optional[torch.LongTensor] = None,
149
+ logits_to_keep: int = 0,
150
+ **kwargs: Unpack[TransformersKwargs],
151
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
152
+ # Get hidden states from the base model (it already builds the multimodal prefix)
153
+ model_outputs = self.model(
154
+ input_ids=input_ids,
155
+ pixel_values=pixel_values,
156
+ tiling=tiling,
157
+ attention_mask=attention_mask,
158
+ position_ids=position_ids,
159
+ past_key_values=past_key_values,
160
+ inputs_embeds=inputs_embeds,
161
+ labels=None,
162
+ use_cache=use_cache,
163
+ output_attentions=output_attentions,
164
+ output_hidden_states=output_hidden_states,
165
+ return_dict=True,
166
+ cache_position=cache_position,
167
+ logits_to_keep=logits_to_keep,
168
+ )
169
+
170
+ hidden_states = model_outputs.last_hidden_state # [B, T, D]
171
+
172
+ # Compute logits; only keep the tail if requested
173
+ if isinstance(logits_to_keep, int) and logits_to_keep > 0:
174
+ hs = hidden_states[:, -logits_to_keep:, :]
175
+ elif isinstance(logits_to_keep, slice):
176
+ hs = hidden_states[:, logits_to_keep, :]
177
+ else:
178
+ hs = hidden_states
179
+
180
+ logits = self.lm_head(hs) # [B, T', V]
181
+
182
+ loss = None
183
+ if labels is not None:
184
+ # Shift if your training uses standard LM convention; here we assume labels aligned with hs
185
+ loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.vocab_size)
186
+
187
+ return CausalLMOutputWithPast(
188
+ loss=loss,
189
+ logits=logits,
190
+ past_key_values=getattr(model_outputs, "past_key_values", None),
191
+ hidden_states=getattr(model_outputs, "hidden_states", None),
192
+ attentions=getattr(model_outputs, "attentions", None),
193
+ )
194
+
195
+ @classmethod
196
+ def _load_pretrained_model(
197
+ cls,
198
+ model: "PreTrainedModel",
199
+ state_dict: Optional[dict],
200
+ checkpoint_files: Optional[list[str]],
201
+ pretrained_model_name_or_path,
202
+ weights_only: bool = True,
203
+ **kwargs,
204
+ ):
205
+ if checkpoint_files is not None:
206
+ state_dict = {}
207
+ for file in checkpoint_files:
208
+ sd = load_state_dict(file, map_location="cpu", weights_only=weights_only)
209
+ for key, value in sd.items():
210
+ state_dict[key] = value
211
+
212
+ from collections import defaultdict
213
+
214
+ moe_layer_experts = defaultdict(set)
215
+
216
+ for key in state_dict.keys():
217
+ if key.startswith("model.text_model.layers."):
218
+ parts = key.split(".")
219
+ # Expected: model.text_model.layers.{layer}.mlp.experts.{expert_id}.down_proj.weight
220
+ if len(parts) > 6 and parts[5] == "experts" and parts[3].isdigit() and parts[6].isdigit():
221
+ layer_idx = int(parts[3])
222
+ expert_idx = int(parts[6])
223
+ moe_layer_experts[layer_idx].add(expert_idx)
224
+
225
+ moe_layers = {layer: len(experts) for layer, experts in moe_layer_experts.items()}
226
+ for layer_idx, num_experts in moe_layers.items():
227
+ state_dict[f"model.text_model.layers.{layer_idx}.mlp.down_proj.weight"] = torch.stack(
228
+ [
229
+ state_dict[f"model.text_model.layers.{layer_idx}.mlp.experts.{i}.down_proj.weight"] for i in range(num_experts)
230
+ ]
231
+ )
232
+ for i in range(num_experts):
233
+ del state_dict[f"model.text_model.layers.{layer_idx}.mlp.experts.{i}.down_proj.weight"]
234
+
235
+ state_dict[f"model.text_model.layers.{layer_idx}.mlp.up_proj.weight"] = torch.stack(
236
+ [
237
+ state_dict[f"model.text_model.layers.{layer_idx}.mlp.experts.{i}.up_proj.weight"] for i in range(num_experts)
238
+ ]
239
+ )
240
+ for i in range(num_experts):
241
+ del state_dict[f"model.text_model.layers.{layer_idx}.mlp.experts.{i}.up_proj.weight"]
242
+
243
+ state_dict[f"model.text_model.layers.{layer_idx}.mlp.gate_proj.weight"] = torch.stack(
244
+ [
245
+ state_dict[f"model.text_model.layers.{layer_idx}.mlp.experts.{i}.gate_proj.weight"] for i in range(num_experts)
246
+ ]
247
+ )
248
+ for i in range(num_experts):
249
+ del state_dict[f"model.text_model.layers.{layer_idx}.mlp.experts.{i}.gate_proj.weight"]
250
+ checkpoint_files = None
251
+
252
+ model, missing_keys, unexpected_keys, mismatched_keys, disk_offload_index, error_msgs = super()._load_pretrained_model(
253
+ model,
254
+ state_dict,
255
+ checkpoint_files,
256
+ pretrained_model_name_or_path,
257
+ **kwargs,
258
+ )
259
+ return model, missing_keys, unexpected_keys, mismatched_keys, disk_offload_index, error_msgs
260
+
261
+ def _fix_state_dict_keys_on_save(self, state_dict: dict):
262
+ for layer_idx in range(self.config.text_config.moe_start_layer, self.config.text_config.num_hidden_layers):
263
+ layer_key = f"model.text_model.layers.{layer_idx}"
264
+ tensor = state_dict.pop(f"{layer_key}.mlp.down_proj.weight").cpu()
265
+ for i, t in enumerate(torch.unbind(tensor)):
266
+ base_key = f"{layer_key}.mlp.experts.{i}"
267
+ state_dict[f"{base_key}.down_proj.weight"] = t.contiguous()
268
+
269
+ tensor = state_dict.pop(f"{layer_key}.mlp.up_proj.weight").cpu()
270
+ for i, t in enumerate(torch.unbind(tensor)):
271
+ base_key = f"{layer_key}.mlp.experts.{i}"
272
+ state_dict[f"{base_key}.up_proj.weight"] = t.contiguous()
273
+
274
+ tensor = state_dict.pop(f"{layer_key}.mlp.gate_proj.weight").cpu()
275
+ for i, t in enumerate(torch.unbind(tensor)):
276
+ base_key = f"{layer_key}.mlp.experts.{i}"
277
+ state_dict[f"{base_key}.gate_proj.weight"] = t.contiguous()
278
+ return state_dict
279
+
280
+
281
+ @staticmethod
282
+ def _reorder_cache(past_key_values, beam_idx):
283
+ reordered_past = ()
284
+ for layer_past in past_key_values:
285
+ reordered_past += (
286
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
287
+ )
288
+ return reordered_past
289
+
290
+
291
+ __all__ = [
292
+ "Moondream3Config",
293
+ "Moondream3TextConfig",
294
+ "Moondream3VisionConfig",
295
+ "Moondream3RegionConfig",
296
+ "Moondream3PreTrainedModel",
297
+ "Moondream3Model",
298
+ "Moondream3TextModel",
299
+ "Moondream3VisionModel",
300
+ "Moondream3ForConditionalGeneration",
301
+ ]
moondream3_moe_fused/functional.py ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+
3
+ from .grouped_gemm.interface import grouped_gemm
4
+
5
+
6
+ # output[b, o] = sum_i weight[selected_experts[b], o, i] * input[b, i]
7
+ def _moe_fused_linear_naive_fwd(
8
+ input: torch.Tensor, weight: torch.Tensor, selected_experts: torch.Tensor
9
+ ) -> torch.Tensor:
10
+ """
11
+ Computes a MoE linear operation.
12
+
13
+ The operation is defined as:
14
+ `output[b, o] = sum_i weight[selected_experts[b], o, i] * input[b, i]`
15
+
16
+ Args:
17
+ input (`torch.FloatTensor`): input tensor of shape `(batch_size, in_features)`.
18
+ weight (`torch.FloatTensor`): weight tensor of shape `(num_experts, out_features, in_features)`.
19
+ selected_experts (`torch.LongTensor`): tensor of selected expert indices in shape `(batch_size,)`.
20
+ Each element is in the range `[0, num_experts)`.
21
+
22
+ Returns:
23
+ output (`torch.FloatTensor`): output tensor of shape `(batch_size, out_features)`.
24
+ """
25
+ batch_size, in_features = input.shape
26
+ num_experts, out_features, _ = weight.shape
27
+
28
+ output = torch.empty(batch_size, out_features, device=input.device, dtype=input.dtype)
29
+ for b in range(batch_size):
30
+ _weight = weight[selected_experts[b], :, :]
31
+ _input = input[b, :]
32
+ output[b, :] = _weight @ _input
33
+ return output
34
+
35
+
36
+ # grad_input[b, i] = sum_o weight[selected_experts[b], o, i] * grad_output[b, o]
37
+ def _moe_fused_linear_naive_bwd_input(
38
+ grad_output: torch.Tensor, input: torch.Tensor, weight: torch.Tensor, selected_experts: torch.Tensor
39
+ ) -> torch.Tensor:
40
+ batch_size, in_features = input.shape
41
+ num_experts, out_features, _ = weight.shape
42
+
43
+ grad_input = torch.empty_like(input)
44
+ for b in range(batch_size):
45
+ _weight = weight[selected_experts[b], :, :]
46
+ _grad_output = grad_output[b, :]
47
+ grad_input[b, :] = _grad_output @ _weight
48
+ return grad_input
49
+
50
+
51
+ # grad_weight[e, o, i] = sum_b if(selected_experts[b] == e) grad_output[b, o] * input[b, i]
52
+ def _moe_fused_linear_naive_bwd_weight(
53
+ grad_output: torch.Tensor, input: torch.Tensor, weight: torch.Tensor, selected_experts: torch.Tensor
54
+ ) -> torch.Tensor:
55
+ batch_size, in_features = input.shape
56
+ num_experts, out_features, _ = weight.shape
57
+
58
+ grad_weight = torch.zeros_like(weight)
59
+ for b in range(batch_size):
60
+ grad_weight[selected_experts[b], :, :] += grad_output[b, :, None] * input[b, None, :]
61
+ return grad_weight
62
+
63
+
64
+ def moe_fused_linear(input: torch.Tensor, weight: torch.Tensor, m_sizes: torch.Tensor) -> torch.Tensor:
65
+ """
66
+ Computes a MoE linear operation using grouped GEMM.
67
+
68
+ The operation is defined as:
69
+ `output[b, o] = sum_i weight[selected_experts[b], o, i] * input[b, i]`
70
+
71
+ Args:
72
+ input (`torch.FloatTensor`): input tensor of shape `(batch_size, in_features)`.
73
+ weight (`torch.FloatTensor`): weight tensor of shape `(num_experts, out_features, in_features)`.
74
+ m_sizes (`torch.LongTensor`): counts of selected experts in shape `(num_experts)`. Should sum to `batch_size`.
75
+
76
+ Returns:
77
+ output (`torch.FloatTensor`): output tensor of shape `(batch_size, out_features)`.
78
+ """
79
+ return grouped_gemm(input, weight, m_sizes)
moondream3_moe_fused/grouped_gemm/LICENSE ADDED
@@ -0,0 +1,661 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ GNU AFFERO GENERAL PUBLIC LICENSE
2
+ Version 3, 19 November 2007
3
+
4
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
5
+ Everyone is permitted to copy and distribute verbatim copies
6
+ of this license document, but changing it is not allowed.
7
+
8
+ Preamble
9
+
10
+ The GNU Affero General Public License is a free, copyleft license for
11
+ software and other kinds of works, specifically designed to ensure
12
+ cooperation with the community in the case of network server software.
13
+
14
+ The licenses for most software and other practical works are designed
15
+ to take away your freedom to share and change the works. By contrast,
16
+ our General Public Licenses are intended to guarantee your freedom to
17
+ share and change all versions of a program--to make sure it remains free
18
+ software for all its users.
19
+
20
+ When we speak of free software, we are referring to freedom, not
21
+ price. Our General Public Licenses are designed to make sure that you
22
+ have the freedom to distribute copies of free software (and charge for
23
+ them if you wish), that you receive source code or can get it if you
24
+ want it, that you can change the software or use pieces of it in new
25
+ free programs, and that you know you can do these things.
26
+
27
+ Developers that use our General Public Licenses protect your rights
28
+ with two steps: (1) assert copyright on the software, and (2) offer
29
+ you this License which gives you legal permission to copy, distribute
30
+ and/or modify the software.
31
+
32
+ A secondary benefit of defending all users' freedom is that
33
+ improvements made in alternate versions of the program, if they
34
+ receive widespread use, become available for other developers to
35
+ incorporate. Many developers of free software are heartened and
36
+ encouraged by the resulting cooperation. However, in the case of
37
+ software used on network servers, this result may fail to come about.
38
+ The GNU General Public License permits making a modified version and
39
+ letting the public access it on a server without ever releasing its
40
+ source code to the public.
41
+
42
+ The GNU Affero General Public License is designed specifically to
43
+ ensure that, in such cases, the modified source code becomes available
44
+ to the community. It requires the operator of a network server to
45
+ provide the source code of the modified version running there to the
46
+ users of that server. Therefore, public use of a modified version, on
47
+ a publicly accessible server, gives the public access to the source
48
+ code of the modified version.
49
+
50
+ An older license, called the Affero General Public License and
51
+ published by Affero, was designed to accomplish similar goals. This is
52
+ a different license, not a version of the Affero GPL, but Affero has
53
+ released a new version of the Affero GPL which permits relicensing under
54
+ this license.
55
+
56
+ The precise terms and conditions for copying, distribution and
57
+ modification follow.
58
+
59
+ TERMS AND CONDITIONS
60
+
61
+ 0. Definitions.
62
+
63
+ "This License" refers to version 3 of the GNU Affero General Public License.
64
+
65
+ "Copyright" also means copyright-like laws that apply to other kinds of
66
+ works, such as semiconductor masks.
67
+
68
+ "The Program" refers to any copyrightable work licensed under this
69
+ License. Each licensee is addressed as "you". "Licensees" and
70
+ "recipients" may be individuals or organizations.
71
+
72
+ To "modify" a work means to copy from or adapt all or part of the work
73
+ in a fashion requiring copyright permission, other than the making of an
74
+ exact copy. The resulting work is called a "modified version" of the
75
+ earlier work or a work "based on" the earlier work.
76
+
77
+ A "covered work" means either the unmodified Program or a work based
78
+ on the Program.
79
+
80
+ To "propagate" a work means to do anything with it that, without
81
+ permission, would make you directly or secondarily liable for
82
+ infringement under applicable copyright law, except executing it on a
83
+ computer or modifying a private copy. Propagation includes copying,
84
+ distribution (with or without modification), making available to the
85
+ public, and in some countries other activities as well.
86
+
87
+ To "convey" a work means any kind of propagation that enables other
88
+ parties to make or receive copies. Mere interaction with a user through
89
+ a computer network, with no transfer of a copy, is not conveying.
90
+
91
+ An interactive user interface displays "Appropriate Legal Notices"
92
+ to the extent that it includes a convenient and prominently visible
93
+ feature that (1) displays an appropriate copyright notice, and (2)
94
+ tells the user that there is no warranty for the work (except to the
95
+ extent that warranties are provided), that licensees may convey the
96
+ work under this License, and how to view a copy of this License. If
97
+ the interface presents a list of user commands or options, such as a
98
+ menu, a prominent item in the list meets this criterion.
99
+
100
+ 1. Source Code.
101
+
102
+ The "source code" for a work means the preferred form of the work
103
+ for making modifications to it. "Object code" means any non-source
104
+ form of a work.
105
+
106
+ A "Standard Interface" means an interface that either is an official
107
+ standard defined by a recognized standards body, or, in the case of
108
+ interfaces specified for a particular programming language, one that
109
+ is widely used among developers working in that language.
110
+
111
+ The "System Libraries" of an executable work include anything, other
112
+ than the work as a whole, that (a) is included in the normal form of
113
+ packaging a Major Component, but which is not part of that Major
114
+ Component, and (b) serves only to enable use of the work with that
115
+ Major Component, or to implement a Standard Interface for which an
116
+ implementation is available to the public in source code form. A
117
+ "Major Component", in this context, means a major essential component
118
+ (kernel, window system, and so on) of the specific operating system
119
+ (if any) on which the executable work runs, or a compiler used to
120
+ produce the work, or an object code interpreter used to run it.
121
+
122
+ The "Corresponding Source" for a work in object code form means all
123
+ the source code needed to generate, install, and (for an executable
124
+ work) run the object code and to modify the work, including scripts to
125
+ control those activities. However, it does not include the work's
126
+ System Libraries, or general-purpose tools or generally available free
127
+ programs which are used unmodified in performing those activities but
128
+ which are not part of the work. For example, Corresponding Source
129
+ includes interface definition files associated with source files for
130
+ the work, and the source code for shared libraries and dynamically
131
+ linked subprograms that the work is specifically designed to require,
132
+ such as by intimate data communication or control flow between those
133
+ subprograms and other parts of the work.
134
+
135
+ The Corresponding Source need not include anything that users
136
+ can regenerate automatically from other parts of the Corresponding
137
+ Source.
138
+
139
+ The Corresponding Source for a work in source code form is that
140
+ same work.
141
+
142
+ 2. Basic Permissions.
143
+
144
+ All rights granted under this License are granted for the term of
145
+ copyright on the Program, and are irrevocable provided the stated
146
+ conditions are met. This License explicitly affirms your unlimited
147
+ permission to run the unmodified Program. The output from running a
148
+ covered work is covered by this License only if the output, given its
149
+ content, constitutes a covered work. This License acknowledges your
150
+ rights of fair use or other equivalent, as provided by copyright law.
151
+
152
+ You may make, run and propagate covered works that you do not
153
+ convey, without conditions so long as your license otherwise remains
154
+ in force. You may convey covered works to others for the sole purpose
155
+ of having them make modifications exclusively for you, or provide you
156
+ with facilities for running those works, provided that you comply with
157
+ the terms of this License in conveying all material for which you do
158
+ not control copyright. Those thus making or running the covered works
159
+ for you must do so exclusively on your behalf, under your direction
160
+ and control, on terms that prohibit them from making any copies of
161
+ your copyrighted material outside their relationship with you.
162
+
163
+ Conveying under any other circumstances is permitted solely under
164
+ the conditions stated below. Sublicensing is not allowed; section 10
165
+ makes it unnecessary.
166
+
167
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
168
+
169
+ No covered work shall be deemed part of an effective technological
170
+ measure under any applicable law fulfilling obligations under article
171
+ 11 of the WIPO copyright treaty adopted on 20 December 1996, or
172
+ similar laws prohibiting or restricting circumvention of such
173
+ measures.
174
+
175
+ When you convey a covered work, you waive any legal power to forbid
176
+ circumvention of technological measures to the extent such circumvention
177
+ is effected by exercising rights under this License with respect to
178
+ the covered work, and you disclaim any intention to limit operation or
179
+ modification of the work as a means of enforcing, against the work's
180
+ users, your or third parties' legal rights to forbid circumvention of
181
+ technological measures.
182
+
183
+ 4. Conveying Verbatim Copies.
184
+
185
+ You may convey verbatim copies of the Program's source code as you
186
+ receive it, in any medium, provided that you conspicuously and
187
+ appropriately publish on each copy an appropriate copyright notice;
188
+ keep intact all notices stating that this License and any
189
+ non-permissive terms added in accord with section 7 apply to the code;
190
+ keep intact all notices of the absence of any warranty; and give all
191
+ recipients a copy of this License along with the Program.
192
+
193
+ You may charge any price or no price for each copy that you convey,
194
+ and you may offer support or warranty protection for a fee.
195
+
196
+ 5. Conveying Modified Source Versions.
197
+
198
+ You may convey a work based on the Program, or the modifications to
199
+ produce it from the Program, in the form of source code under the
200
+ terms of section 4, provided that you also meet all of these conditions:
201
+
202
+ a) The work must carry prominent notices stating that you modified
203
+ it, and giving a relevant date.
204
+
205
+ b) The work must carry prominent notices stating that it is
206
+ released under this License and any conditions added under section
207
+ 7. This requirement modifies the requirement in section 4 to
208
+ "keep intact all notices".
209
+
210
+ c) You must license the entire work, as a whole, under this
211
+ License to anyone who comes into possession of a copy. This
212
+ License will therefore apply, along with any applicable section 7
213
+ additional terms, to the whole of the work, and all its parts,
214
+ regardless of how they are packaged. This License gives no
215
+ permission to license the work in any other way, but it does not
216
+ invalidate such permission if you have separately received it.
217
+
218
+ d) If the work has interactive user interfaces, each must display
219
+ Appropriate Legal Notices; however, if the Program has interactive
220
+ interfaces that do not display Appropriate Legal Notices, your
221
+ work need not make them do so.
222
+
223
+ A compilation of a covered work with other separate and independent
224
+ works, which are not by their nature extensions of the covered work,
225
+ and which are not combined with it such as to form a larger program,
226
+ in or on a volume of a storage or distribution medium, is called an
227
+ "aggregate" if the compilation and its resulting copyright are not
228
+ used to limit the access or legal rights of the compilation's users
229
+ beyond what the individual works permit. Inclusion of a covered work
230
+ in an aggregate does not cause this License to apply to the other
231
+ parts of the aggregate.
232
+
233
+ 6. Conveying Non-Source Forms.
234
+
235
+ You may convey a covered work in object code form under the terms
236
+ of sections 4 and 5, provided that you also convey the
237
+ machine-readable Corresponding Source under the terms of this License,
238
+ in one of these ways:
239
+
240
+ a) Convey the object code in, or embodied in, a physical product
241
+ (including a physical distribution medium), accompanied by the
242
+ Corresponding Source fixed on a durable physical medium
243
+ customarily used for software interchange.
244
+
245
+ b) Convey the object code in, or embodied in, a physical product
246
+ (including a physical distribution medium), accompanied by a
247
+ written offer, valid for at least three years and valid for as
248
+ long as you offer spare parts or customer support for that product
249
+ model, to give anyone who possesses the object code either (1) a
250
+ copy of the Corresponding Source for all the software in the
251
+ product that is covered by this License, on a durable physical
252
+ medium customarily used for software interchange, for a price no
253
+ more than your reasonable cost of physically performing this
254
+ conveying of source, or (2) access to copy the
255
+ Corresponding Source from a network server at no charge.
256
+
257
+ c) Convey individual copies of the object code with a copy of the
258
+ written offer to provide the Corresponding Source. This
259
+ alternative is allowed only occasionally and noncommercially, and
260
+ only if you received the object code with such an offer, in accord
261
+ with subsection 6b.
262
+
263
+ d) Convey the object code by offering access from a designated
264
+ place (gratis or for a charge), and offer equivalent access to the
265
+ Corresponding Source in the same way through the same place at no
266
+ further charge. You need not require recipients to copy the
267
+ Corresponding Source along with the object code. If the place to
268
+ copy the object code is a network server, the Corresponding Source
269
+ may be on a different server (operated by you or a third party)
270
+ that supports equivalent copying facilities, provided you maintain
271
+ clear directions next to the object code saying where to find the
272
+ Corresponding Source. Regardless of what server hosts the
273
+ Corresponding Source, you remain obligated to ensure that it is
274
+ available for as long as needed to satisfy these requirements.
275
+
276
+ e) Convey the object code using peer-to-peer transmission, provided
277
+ you inform other peers where the object code and Corresponding
278
+ Source of the work are being offered to the general public at no
279
+ charge under subsection 6d.
280
+
281
+ A separable portion of the object code, whose source code is excluded
282
+ from the Corresponding Source as a System Library, need not be
283
+ included in conveying the object code work.
284
+
285
+ A "User Product" is either (1) a "consumer product", which means any
286
+ tangible personal property which is normally used for personal, family,
287
+ or household purposes, or (2) anything designed or sold for incorporation
288
+ into a dwelling. In determining whether a product is a consumer product,
289
+ doubtful cases shall be resolved in favor of coverage. For a particular
290
+ product received by a particular user, "normally used" refers to a
291
+ typical or common use of that class of product, regardless of the status
292
+ of the particular user or of the way in which the particular user
293
+ actually uses, or expects or is expected to use, the product. A product
294
+ is a consumer product regardless of whether the product has substantial
295
+ commercial, industrial or non-consumer uses, unless such uses represent
296
+ the only significant mode of use of the product.
297
+
298
+ "Installation Information" for a User Product means any methods,
299
+ procedures, authorization keys, or other information required to install
300
+ and execute modified versions of a covered work in that User Product from
301
+ a modified version of its Corresponding Source. The information must
302
+ suffice to ensure that the continued functioning of the modified object
303
+ code is in no case prevented or interfered with solely because
304
+ modification has been made.
305
+
306
+ If you convey an object code work under this section in, or with, or
307
+ specifically for use in, a User Product, and the conveying occurs as
308
+ part of a transaction in which the right of possession and use of the
309
+ User Product is transferred to the recipient in perpetuity or for a
310
+ fixed term (regardless of how the transaction is characterized), the
311
+ Corresponding Source conveyed under this section must be accompanied
312
+ by the Installation Information. But this requirement does not apply
313
+ if neither you nor any third party retains the ability to install
314
+ modified object code on the User Product (for example, the work has
315
+ been installed in ROM).
316
+
317
+ The requirement to provide Installation Information does not include a
318
+ requirement to continue to provide support service, warranty, or updates
319
+ for a work that has been modified or installed by the recipient, or for
320
+ the User Product in which it has been modified or installed. Access to a
321
+ network may be denied when the modification itself materially and
322
+ adversely affects the operation of the network or violates the rules and
323
+ protocols for communication across the network.
324
+
325
+ Corresponding Source conveyed, and Installation Information provided,
326
+ in accord with this section must be in a format that is publicly
327
+ documented (and with an implementation available to the public in
328
+ source code form), and must require no special password or key for
329
+ unpacking, reading or copying.
330
+
331
+ 7. Additional Terms.
332
+
333
+ "Additional permissions" are terms that supplement the terms of this
334
+ License by making exceptions from one or more of its conditions.
335
+ Additional permissions that are applicable to the entire Program shall
336
+ be treated as though they were included in this License, to the extent
337
+ that they are valid under applicable law. If additional permissions
338
+ apply only to part of the Program, that part may be used separately
339
+ under those permissions, but the entire Program remains governed by
340
+ this License without regard to the additional permissions.
341
+
342
+ When you convey a copy of a covered work, you may at your option
343
+ remove any additional permissions from that copy, or from any part of
344
+ it. (Additional permissions may be written to require their own
345
+ removal in certain cases when you modify the work.) You may place
346
+ additional permissions on material, added by you to a covered work,
347
+ for which you have or can give appropriate copyright permission.
348
+
349
+ Notwithstanding any other provision of this License, for material you
350
+ add to a covered work, you may (if authorized by the copyright holders of
351
+ that material) supplement the terms of this License with terms:
352
+
353
+ a) Disclaiming warranty or limiting liability differently from the
354
+ terms of sections 15 and 16 of this License; or
355
+
356
+ b) Requiring preservation of specified reasonable legal notices or
357
+ author attributions in that material or in the Appropriate Legal
358
+ Notices displayed by works containing it; or
359
+
360
+ c) Prohibiting misrepresentation of the origin of that material, or
361
+ requiring that modified versions of such material be marked in
362
+ reasonable ways as different from the original version; or
363
+
364
+ d) Limiting the use for publicity purposes of names of licensors or
365
+ authors of the material; or
366
+
367
+ e) Declining to grant rights under trademark law for use of some
368
+ trade names, trademarks, or service marks; or
369
+
370
+ f) Requiring indemnification of licensors and authors of that
371
+ material by anyone who conveys the material (or modified versions of
372
+ it) with contractual assumptions of liability to the recipient, for
373
+ any liability that these contractual assumptions directly impose on
374
+ those licensors and authors.
375
+
376
+ All other non-permissive additional terms are considered "further
377
+ restrictions" within the meaning of section 10. If the Program as you
378
+ received it, or any part of it, contains a notice stating that it is
379
+ governed by this License along with a term that is a further
380
+ restriction, you may remove that term. If a license document contains
381
+ a further restriction but permits relicensing or conveying under this
382
+ License, you may add to a covered work material governed by the terms
383
+ of that license document, provided that the further restriction does
384
+ not survive such relicensing or conveying.
385
+
386
+ If you add terms to a covered work in accord with this section, you
387
+ must place, in the relevant source files, a statement of the
388
+ additional terms that apply to those files, or a notice indicating
389
+ where to find the applicable terms.
390
+
391
+ Additional terms, permissive or non-permissive, may be stated in the
392
+ form of a separately written license, or stated as exceptions;
393
+ the above requirements apply either way.
394
+
395
+ 8. Termination.
396
+
397
+ You may not propagate or modify a covered work except as expressly
398
+ provided under this License. Any attempt otherwise to propagate or
399
+ modify it is void, and will automatically terminate your rights under
400
+ this License (including any patent licenses granted under the third
401
+ paragraph of section 11).
402
+
403
+ However, if you cease all violation of this License, then your
404
+ license from a particular copyright holder is reinstated (a)
405
+ provisionally, unless and until the copyright holder explicitly and
406
+ finally terminates your license, and (b) permanently, if the copyright
407
+ holder fails to notify you of the violation by some reasonable means
408
+ prior to 60 days after the cessation.
409
+
410
+ Moreover, your license from a particular copyright holder is
411
+ reinstated permanently if the copyright holder notifies you of the
412
+ violation by some reasonable means, this is the first time you have
413
+ received notice of violation of this License (for any work) from that
414
+ copyright holder, and you cure the violation prior to 30 days after
415
+ your receipt of the notice.
416
+
417
+ Termination of your rights under this section does not terminate the
418
+ licenses of parties who have received copies or rights from you under
419
+ this License. If your rights have been terminated and not permanently
420
+ reinstated, you do not qualify to receive new licenses for the same
421
+ material under section 10.
422
+
423
+ 9. Acceptance Not Required for Having Copies.
424
+
425
+ You are not required to accept this License in order to receive or
426
+ run a copy of the Program. Ancillary propagation of a covered work
427
+ occurring solely as a consequence of using peer-to-peer transmission
428
+ to receive a copy likewise does not require acceptance. However,
429
+ nothing other than this License grants you permission to propagate or
430
+ modify any covered work. These actions infringe copyright if you do
431
+ not accept this License. Therefore, by modifying or propagating a
432
+ covered work, you indicate your acceptance of this License to do so.
433
+
434
+ 10. Automatic Licensing of Downstream Recipients.
435
+
436
+ Each time you convey a covered work, the recipient automatically
437
+ receives a license from the original licensors, to run, modify and
438
+ propagate that work, subject to this License. You are not responsible
439
+ for enforcing compliance by third parties with this License.
440
+
441
+ An "entity transaction" is a transaction transferring control of an
442
+ organization, or substantially all assets of one, or subdividing an
443
+ organization, or merging organizations. If propagation of a covered
444
+ work results from an entity transaction, each party to that
445
+ transaction who receives a copy of the work also receives whatever
446
+ licenses to the work the party's predecessor in interest had or could
447
+ give under the previous paragraph, plus a right to possession of the
448
+ Corresponding Source of the work from the predecessor in interest, if
449
+ the predecessor has it or can get it with reasonable efforts.
450
+
451
+ You may not impose any further restrictions on the exercise of the
452
+ rights granted or affirmed under this License. For example, you may
453
+ not impose a license fee, royalty, or other charge for exercise of
454
+ rights granted under this License, and you may not initiate litigation
455
+ (including a cross-claim or counterclaim in a lawsuit) alleging that
456
+ any patent claim is infringed by making, using, selling, offering for
457
+ sale, or importing the Program or any portion of it.
458
+
459
+ 11. Patents.
460
+
461
+ A "contributor" is a copyright holder who authorizes use under this
462
+ License of the Program or a work on which the Program is based. The
463
+ work thus licensed is called the contributor's "contributor version".
464
+
465
+ A contributor's "essential patent claims" are all patent claims
466
+ owned or controlled by the contributor, whether already acquired or
467
+ hereafter acquired, that would be infringed by some manner, permitted
468
+ by this License, of making, using, or selling its contributor version,
469
+ but do not include claims that would be infringed only as a
470
+ consequence of further modification of the contributor version. For
471
+ purposes of this definition, "control" includes the right to grant
472
+ patent sublicenses in a manner consistent with the requirements of
473
+ this License.
474
+
475
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
476
+ patent license under the contributor's essential patent claims, to
477
+ make, use, sell, offer for sale, import and otherwise run, modify and
478
+ propagate the contents of its contributor version.
479
+
480
+ In the following three paragraphs, a "patent license" is any express
481
+ agreement or commitment, however denominated, not to enforce a patent
482
+ (such as an express permission to practice a patent or covenant not to
483
+ sue for patent infringement). To "grant" such a patent license to a
484
+ party means to make such an agreement or commitment not to enforce a
485
+ patent against the party.
486
+
487
+ If you convey a covered work, knowingly relying on a patent license,
488
+ and the Corresponding Source of the work is not available for anyone
489
+ to copy, free of charge and under the terms of this License, through a
490
+ publicly available network server or other readily accessible means,
491
+ then you must either (1) cause the Corresponding Source to be so
492
+ available, or (2) arrange to deprive yourself of the benefit of the
493
+ patent license for this particular work, or (3) arrange, in a manner
494
+ consistent with the requirements of this License, to extend the patent
495
+ license to downstream recipients. "Knowingly relying" means you have
496
+ actual knowledge that, but for the patent license, your conveying the
497
+ covered work in a country, or your recipient's use of the covered work
498
+ in a country, would infringe one or more identifiable patents in that
499
+ country that you have reason to believe are valid.
500
+
501
+ If, pursuant to or in connection with a single transaction or
502
+ arrangement, you convey, or propagate by procuring conveyance of, a
503
+ covered work, and grant a patent license to some of the parties
504
+ receiving the covered work authorizing them to use, propagate, modify
505
+ or convey a specific copy of the covered work, then the patent license
506
+ you grant is automatically extended to all recipients of the covered
507
+ work and works based on it.
508
+
509
+ A patent license is "discriminatory" if it does not include within
510
+ the scope of its coverage, prohibits the exercise of, or is
511
+ conditioned on the non-exercise of one or more of the rights that are
512
+ specifically granted under this License. You may not convey a covered
513
+ work if you are a party to an arrangement with a third party that is
514
+ in the business of distributing software, under which you make payment
515
+ to the third party based on the extent of your activity of conveying
516
+ the work, and under which the third party grants, to any of the
517
+ parties who would receive the covered work from you, a discriminatory
518
+ patent license (a) in connection with copies of the covered work
519
+ conveyed by you (or copies made from those copies), or (b) primarily
520
+ for and in connection with specific products or compilations that
521
+ contain the covered work, unless you entered into that arrangement,
522
+ or that patent license was granted, prior to 28 March 2007.
523
+
524
+ Nothing in this License shall be construed as excluding or limiting
525
+ any implied license or other defenses to infringement that may
526
+ otherwise be available to you under applicable patent law.
527
+
528
+ 12. No Surrender of Others' Freedom.
529
+
530
+ If conditions are imposed on you (whether by court order, agreement or
531
+ otherwise) that contradict the conditions of this License, they do not
532
+ excuse you from the conditions of this License. If you cannot convey a
533
+ covered work so as to satisfy simultaneously your obligations under this
534
+ License and any other pertinent obligations, then as a consequence you may
535
+ not convey it at all. For example, if you agree to terms that obligate you
536
+ to collect a royalty for further conveying from those to whom you convey
537
+ the Program, the only way you could satisfy both those terms and this
538
+ License would be to refrain entirely from conveying the Program.
539
+
540
+ 13. Remote Network Interaction; Use with the GNU General Public License.
541
+
542
+ Notwithstanding any other provision of this License, if you modify the
543
+ Program, your modified version must prominently offer all users
544
+ interacting with it remotely through a computer network (if your version
545
+ supports such interaction) an opportunity to receive the Corresponding
546
+ Source of your version by providing access to the Corresponding Source
547
+ from a network server at no charge, through some standard or customary
548
+ means of facilitating copying of software. This Corresponding Source
549
+ shall include the Corresponding Source for any work covered by version 3
550
+ of the GNU General Public License that is incorporated pursuant to the
551
+ following paragraph.
552
+
553
+ Notwithstanding any other provision of this License, you have
554
+ permission to link or combine any covered work with a work licensed
555
+ under version 3 of the GNU General Public License into a single
556
+ combined work, and to convey the resulting work. The terms of this
557
+ License will continue to apply to the part which is the covered work,
558
+ but the work with which it is combined will remain governed by version
559
+ 3 of the GNU General Public License.
560
+
561
+ 14. Revised Versions of this License.
562
+
563
+ The Free Software Foundation may publish revised and/or new versions of
564
+ the GNU Affero General Public License from time to time. Such new versions
565
+ will be similar in spirit to the present version, but may differ in detail to
566
+ address new problems or concerns.
567
+
568
+ Each version is given a distinguishing version number. If the
569
+ Program specifies that a certain numbered version of the GNU Affero General
570
+ Public License "or any later version" applies to it, you have the
571
+ option of following the terms and conditions either of that numbered
572
+ version or of any later version published by the Free Software
573
+ Foundation. If the Program does not specify a version number of the
574
+ GNU Affero General Public License, you may choose any version ever published
575
+ by the Free Software Foundation.
576
+
577
+ If the Program specifies that a proxy can decide which future
578
+ versions of the GNU Affero General Public License can be used, that proxy's
579
+ public statement of acceptance of a version permanently authorizes you
580
+ to choose that version for the Program.
581
+
582
+ Later license versions may give you additional or different
583
+ permissions. However, no additional obligations are imposed on any
584
+ author or copyright holder as a result of your choosing to follow a
585
+ later version.
586
+
587
+ 15. Disclaimer of Warranty.
588
+
589
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
590
+ APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
591
+ HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
592
+ OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
593
+ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
594
+ PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
595
+ IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
596
+ ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
597
+
598
+ 16. Limitation of Liability.
599
+
600
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
601
+ WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
602
+ THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
603
+ GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
604
+ USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
605
+ DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
606
+ PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
607
+ EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
608
+ SUCH DAMAGES.
609
+
610
+ 17. Interpretation of Sections 15 and 16.
611
+
612
+ If the disclaimer of warranty and limitation of liability provided
613
+ above cannot be given local legal effect according to their terms,
614
+ reviewing courts shall apply local law that most closely approximates
615
+ an absolute waiver of all civil liability in connection with the
616
+ Program, unless a warranty or assumption of liability accompanies a
617
+ copy of the Program in return for a fee.
618
+
619
+ END OF TERMS AND CONDITIONS
620
+
621
+ How to Apply These Terms to Your New Programs
622
+
623
+ If you develop a new program, and you want it to be of the greatest
624
+ possible use to the public, the best way to achieve this is to make it
625
+ free software which everyone can redistribute and change under these terms.
626
+
627
+ To do so, attach the following notices to the program. It is safest
628
+ to attach them to the start of each source file to most effectively
629
+ state the exclusion of warranty; and each file should have at least
630
+ the "copyright" line and a pointer to where the full notice is found.
631
+
632
+ <one line to give the program's name and a brief idea of what it does.>
633
+ Copyright (C) <year> <name of author>
634
+
635
+ This program is free software: you can redistribute it and/or modify
636
+ it under the terms of the GNU Affero General Public License as published
637
+ by the Free Software Foundation, either version 3 of the License, or
638
+ (at your option) any later version.
639
+
640
+ This program is distributed in the hope that it will be useful,
641
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
642
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
643
+ GNU Affero General Public License for more details.
644
+
645
+ You should have received a copy of the GNU Affero General Public License
646
+ along with this program. If not, see <https://www.gnu.org/licenses/>.
647
+
648
+ Also add information on how to contact you by electronic and paper mail.
649
+
650
+ If your software can interact with users remotely through a computer
651
+ network, you should also make sure that it provides a way for users to
652
+ get its source. For example, if your program is a web application, its
653
+ interface could display a "Source" link that leads users to an archive
654
+ of the code. There are many ways you could offer source, and different
655
+ solutions will be better for different programs; see section 13 for the
656
+ specific requirements.
657
+
658
+ You should also get your employer (if you work as a programmer) or school,
659
+ if any, to sign a "copyright disclaimer" for the program, if necessary.
660
+ For more information on this, and how to apply and follow the GNU AGPL, see
661
+ <https://www.gnu.org/licenses/>.
moondream3_moe_fused/grouped_gemm/__init__.py ADDED
File without changes
moondream3_moe_fused/grouped_gemm/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (195 Bytes). View file
 
moondream3_moe_fused/grouped_gemm/__pycache__/autotuning.cpython-311.pyc ADDED
Binary file (3.61 kB). View file
 
moondream3_moe_fused/grouped_gemm/__pycache__/backward_dw.cpython-311.pyc ADDED
Binary file (6.49 kB). View file
 
moondream3_moe_fused/grouped_gemm/__pycache__/forward.cpython-311.pyc ADDED
Binary file (7.12 kB). View file
 
moondream3_moe_fused/grouped_gemm/__pycache__/forward_transposed.cpython-311.pyc ADDED
Binary file (6.86 kB). View file
 
moondream3_moe_fused/grouped_gemm/__pycache__/interface.cpython-311.pyc ADDED
Binary file (1.6 kB). View file
 
moondream3_moe_fused/grouped_gemm/autotuning.py ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from itertools import product
3
+ from typing import Any
4
+
5
+ import torch
6
+ import triton
7
+
8
+
9
+ DEFAULT_M_BLOCK_SIZES = [16, 32, 64, 128, 256]
10
+ DEFAULT_N_BLOCK_SIZES = [16, 32, 64, 128, 256]
11
+ DEFAULT_K_BLOCK_SIZES = [16, 32, 64, 128, 256]
12
+ DEFAULT_NUM_WARPS = [4, 8]
13
+ DEFAULT_NUM_STAGES = [3, 4, 5, 6]
14
+
15
+
16
+ def get_num_sms() -> int:
17
+ return torch.cuda.get_device_properties("cuda").multi_processor_count
18
+
19
+
20
+ def get_autotune_configs() -> list[triton.Config]:
21
+ return [
22
+ triton.Config({'BLOCK_SIZE_M': 128, 'BLOCK_SIZE_K': 32, 'BLOCK_SIZE_M': 64}, num_stages=2, num_warps=4),
23
+ ]
24
+
25
+ configs = []
26
+ for m, n, k, w, s in product(
27
+ DEFAULT_M_BLOCK_SIZES,
28
+ DEFAULT_N_BLOCK_SIZES,
29
+ DEFAULT_K_BLOCK_SIZES,
30
+ DEFAULT_NUM_WARPS,
31
+ DEFAULT_NUM_STAGES,
32
+ ):
33
+ configs.append(
34
+ triton.Config({"BLOCK_SIZE_M": m, "BLOCK_SIZE_N": n, "BLOCK_SIZE_K": k}, num_warps=w, num_stages=s)
35
+ )
36
+ return configs
37
+
38
+
39
+ def _get_device_properties() -> dict[str, Any]:
40
+ return triton.runtime.driver.active.utils.get_device_properties(torch.cuda.current_device())
41
+
42
+
43
+ def _exceeds_smem_capacity(
44
+ num_stages: int,
45
+ BLOCK_SIZE_M: int,
46
+ BLOCK_SIZE_N: int,
47
+ BLOCK_SIZE_K: int,
48
+ dtype: torch.dtype,
49
+ smem_size: int,
50
+ slack: int = 0,
51
+ ) -> bool:
52
+ return (
53
+ num_stages * BLOCK_SIZE_K * (BLOCK_SIZE_M + BLOCK_SIZE_N) + BLOCK_SIZE_M * BLOCK_SIZE_N
54
+ ) * dtype.itemsize > smem_size + slack
55
+
56
+
57
+ def _common_prune_criteria(config: triton.Config, kwargs: dict[str, Any]) -> bool:
58
+ return False
59
+ num_stages = config.num_stages
60
+ BLOCK_SIZE_M = config.kwargs["BLOCK_SIZE_M"]
61
+ BLOCK_SIZE_N = config.kwargs["BLOCK_SIZE_N"]
62
+ BLOCK_SIZE_K = config.kwargs["BLOCK_SIZE_K"]
63
+ dtype = kwargs["x_ptr"].dtype
64
+ device_properties = _get_device_properties()
65
+ smem_size = device_properties["max_shared_mem"]
66
+ if _exceeds_smem_capacity(num_stages, BLOCK_SIZE_M, BLOCK_SIZE_N, BLOCK_SIZE_K, dtype, smem_size):
67
+ return True
68
+
69
+ M = kwargs["M"]
70
+ N = kwargs["N"]
71
+ K = kwargs["K"]
72
+ num_experts = kwargs["NUM_EXPERTS"]
73
+ tokens_per_expert = M // num_experts
74
+ max_block_size_M = max(tokens_per_expert * 2, DEFAULT_M_BLOCK_SIZES[0])
75
+ max_block_size_N = max(N, DEFAULT_N_BLOCK_SIZES[0])
76
+ max_block_size_K = max(K, DEFAULT_K_BLOCK_SIZES[0])
77
+ if BLOCK_SIZE_M >= max_block_size_M:
78
+ return True
79
+ if BLOCK_SIZE_N >= max_block_size_N:
80
+ return True
81
+ if BLOCK_SIZE_K >= max_block_size_K:
82
+ return True
83
+
84
+ min_block_size_M = min(triton.next_power_of_2(tokens_per_expert // 2 + 1), 64)
85
+ min_block_size_N = min(triton.next_power_of_2(N // 2 + 1), 64)
86
+ min_block_size_K = min(triton.next_power_of_2(K // 2 + 1), 64)
87
+ if BLOCK_SIZE_M * BLOCK_SIZE_N <= min_block_size_M * min_block_size_N:
88
+ return True
89
+ if BLOCK_SIZE_M * BLOCK_SIZE_K <= min_block_size_M * min_block_size_K:
90
+ return True
91
+ if BLOCK_SIZE_N * BLOCK_SIZE_K <= min_block_size_N * min_block_size_K:
92
+ return True
93
+
94
+ return False
95
+
96
+
97
+ def prune_configs(configs: list[triton.Config], args, **kwargs) -> list[triton.Config]:
98
+ pruned_configs = []
99
+ for config in configs:
100
+ if _common_prune_criteria(config, args):
101
+ continue
102
+ pruned_configs.append(config)
103
+ return pruned_configs
104
+
105
+
106
+ # We need to autotune on batch size only when benchmarking with a large range of batch sizes
107
+ def get_autotune_keys() -> list[str]:
108
+ if os.getenv("AUTOTUNE_BATCH_SIZE", "0") == "1":
109
+ return ["M", "N", "K", "NUM_EXPERTS"]
110
+ else:
111
+ return ["N", "K", "NUM_EXPERTS"]
moondream3_moe_fused/grouped_gemm/backward_dw.py ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # w[e, n, k] = sum_m if(s[m] == e) y[m, n] * x[m, k]
2
+
3
+ import torch
4
+ import triton
5
+ import triton.language as tl
6
+
7
+ from .autotuning import (
8
+ get_autotune_configs,
9
+ get_autotune_keys,
10
+ get_num_sms,
11
+ prune_configs,
12
+ )
13
+ from .forward import is_int_tensor
14
+
15
+
16
+ @triton.autotune(
17
+ configs=get_autotune_configs(),
18
+ prune_configs_by={"early_config_prune": prune_configs},
19
+ key=get_autotune_keys(),
20
+ )
21
+ @triton.jit
22
+ def _grouped_gemm_backward_dw_kernel(
23
+ # Pointers
24
+ x_ptr,
25
+ y_ptr,
26
+ m_sizes_ptr,
27
+ w_ptr,
28
+ # Dimensions
29
+ M: int,
30
+ N: tl.constexpr,
31
+ K: tl.constexpr,
32
+ NUM_EXPERTS: tl.constexpr,
33
+ NUM_SMS: tl.constexpr,
34
+ # Strides
35
+ stride_xm: tl.constexpr,
36
+ stride_xk: tl.constexpr,
37
+ stride_ym: tl.constexpr,
38
+ stride_yn: tl.constexpr,
39
+ stride_we: tl.constexpr,
40
+ stride_wn: tl.constexpr,
41
+ stride_wk: tl.constexpr,
42
+ # Metadata
43
+ BLOCK_SIZE_M: tl.constexpr = 64,
44
+ BLOCK_SIZE_N: tl.constexpr = 64,
45
+ BLOCK_SIZE_K: tl.constexpr = 64,
46
+ ) -> None:
47
+ tidx = tl.program_id(0)
48
+
49
+ # Output tiles per expert, since each expert weight matrix is [N, K]
50
+ num_n_tiles = tl.cdiv(N, BLOCK_SIZE_N)
51
+ num_k_tiles = tl.cdiv(K, BLOCK_SIZE_K)
52
+ num_tiles_per_expert = num_n_tiles * num_k_tiles
53
+
54
+ for tile_idx in range(tidx, num_tiles_per_expert, NUM_SMS):
55
+ # Output tile index
56
+ tile_n_idx = tile_idx % num_n_tiles
57
+ tile_k_idx = tile_idx // num_n_tiles
58
+
59
+ offs_n = tile_n_idx * BLOCK_SIZE_N + tl.arange(0, BLOCK_SIZE_N)
60
+ offs_k = tile_k_idx * BLOCK_SIZE_K + tl.arange(0, BLOCK_SIZE_K)
61
+ mask_n = offs_n < N
62
+ mask_k = offs_k < K
63
+
64
+ m_end = 0
65
+ for expert_idx in range(NUM_EXPERTS):
66
+ m_start = m_end
67
+ m_size = tl.load(m_sizes_ptr + expert_idx).to(tl.int32)
68
+ m_end = m_start + m_size
69
+ if m_size > 0:
70
+ offs_m = m_start + tl.arange(0, BLOCK_SIZE_M)
71
+
72
+ x_ptrs = x_ptr + stride_xm * offs_m[:, None] + stride_xk * offs_k[None, :]
73
+ y_ptrs = y_ptr + stride_ym * offs_m[:, None] + stride_yn * offs_n[None, :]
74
+
75
+ accumulator = tl.zeros((BLOCK_SIZE_N, BLOCK_SIZE_K), dtype=tl.float32)
76
+ for _ in range(tl.cdiv(m_size, BLOCK_SIZE_M)):
77
+ mask_m = offs_m < m_end
78
+ x = tl.load(x_ptrs, mask=mask_m[:, None] & mask_k[None, :])
79
+ y = tl.load(y_ptrs, mask=mask_m[:, None] & mask_n[None, :])
80
+
81
+ accumulator += tl.dot(y.T, x)
82
+
83
+ offs_m += BLOCK_SIZE_M
84
+ x_ptrs += stride_xm * BLOCK_SIZE_M
85
+ y_ptrs += stride_ym * BLOCK_SIZE_M
86
+ w = accumulator.to(w_ptr.dtype.element_ty)
87
+
88
+ w_ptrs = w_ptr + stride_we * expert_idx + stride_wn * offs_n[:, None] + stride_wk * offs_k[None, :]
89
+ tl.store(w_ptrs, w, mask=mask_n[:, None] & mask_k[None, :])
90
+
91
+
92
+ def grouped_gemm_backward_dw(
93
+ x: torch.Tensor, y: torch.Tensor, m_sizes: torch.Tensor, dtype: torch.dtype
94
+ ) -> torch.Tensor:
95
+ assert x.is_cuda
96
+ assert y.device == x.device
97
+ assert m_sizes.device == x.device
98
+ assert is_int_tensor(m_sizes)
99
+ assert x.is_contiguous()
100
+ assert y.is_contiguous()
101
+ assert m_sizes.is_contiguous()
102
+ assert x.ndim == 2
103
+ assert y.ndim == 2
104
+ assert m_sizes.ndim == 1
105
+ M, K = x.shape
106
+ _, N = y.shape
107
+ assert y.shape[0] == M
108
+ E = m_sizes.numel()
109
+
110
+ w = torch.zeros((E, N, K), device=x.device, dtype=dtype)
111
+ NUM_SMS = get_num_sms()
112
+ grid = lambda META: (NUM_SMS,)
113
+ with torch.cuda.device(x.device):
114
+ _grouped_gemm_backward_dw_kernel[grid](
115
+ # Pointers
116
+ x,
117
+ y,
118
+ m_sizes,
119
+ w,
120
+ # Dimensions
121
+ M,
122
+ N,
123
+ K,
124
+ E,
125
+ NUM_SMS,
126
+ # Strides
127
+ x.stride(0),
128
+ x.stride(1),
129
+ y.stride(0),
130
+ y.stride(1),
131
+ w.stride(0),
132
+ w.stride(1),
133
+ w.stride(2),
134
+ )
135
+ return w
moondream3_moe_fused/grouped_gemm/forward.py ADDED
@@ -0,0 +1,164 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # y[m, n] = sum_k w[s[m], n, k] * x[m, k]
2
+
3
+ from typing import Optional
4
+
5
+ import torch
6
+ import triton
7
+ import triton.language as tl
8
+
9
+ from .autotuning import (
10
+ get_autotune_configs,
11
+ get_autotune_keys,
12
+ get_num_sms,
13
+ prune_configs,
14
+ )
15
+
16
+
17
+ @triton.autotune(
18
+ configs=get_autotune_configs(),
19
+ # configs=[
20
+ # triton.Config({'BLOCK_SIZE_M': 128, 'BLOCK_SIZE_K': 32, 'BLOCK_SIZE_M': 128}, num_stages=4, num_warps=4),
21
+ # ],
22
+ prune_configs_by={"early_config_prune": prune_configs},
23
+ key=get_autotune_keys(),
24
+ )
25
+ @triton.jit
26
+ def _grouped_gemm_forward_kernel(
27
+ # Pointers
28
+ x_ptr,
29
+ w_ptr,
30
+ m_sizes_ptr,
31
+ y_ptr,
32
+ # Dimensions
33
+ M: int,
34
+ N: tl.constexpr,
35
+ K: tl.constexpr,
36
+ NUM_EXPERTS: tl.constexpr,
37
+ NUM_SMS: tl.constexpr,
38
+ # Strides
39
+ stride_xm: tl.constexpr,
40
+ stride_xk: tl.constexpr,
41
+ stride_we: tl.constexpr,
42
+ stride_wn: tl.constexpr,
43
+ stride_wk: tl.constexpr,
44
+ stride_ym: tl.constexpr,
45
+ stride_yn: tl.constexpr,
46
+ # Metadata
47
+ BLOCK_SIZE_M: tl.constexpr = 64,
48
+ BLOCK_SIZE_N: tl.constexpr = 64,
49
+ BLOCK_SIZE_K: tl.constexpr = 64,
50
+ ) -> None:
51
+ tidx = tl.program_id(0)
52
+ m_end = 0
53
+ processed_tiles = 0
54
+ for expert_idx in range(NUM_EXPERTS):
55
+ m_start = m_end
56
+ m_size = tl.load(m_sizes_ptr + expert_idx).to(tl.int32)
57
+ m_end = m_start + m_size
58
+ if m_size > 0:
59
+ # tiles for this group's GEMM
60
+ num_m_tiles = tl.cdiv(m_size, BLOCK_SIZE_M)
61
+ num_n_tiles = tl.cdiv(N, BLOCK_SIZE_N)
62
+ num_tiles_per_expert = num_m_tiles * num_n_tiles
63
+
64
+ # Lower bound and upper bound are defined relative to the total tiles processed so far
65
+ # This ensures that we are only processing tiles for the current expert group AND
66
+ # we never exceed the total number of tiles for all expert groups
67
+ while tidx >= processed_tiles and tidx < processed_tiles + num_tiles_per_expert:
68
+ tile_idx = tidx - processed_tiles
69
+
70
+ # Output tile for this thread block for this expert group
71
+ # TODO: Check if L2 cache re-use for this order is optimal
72
+ tile_m_idx = tile_idx % num_m_tiles
73
+ tile_n_idx = tile_idx // num_m_tiles
74
+
75
+ offs_k = tl.arange(0, BLOCK_SIZE_K)
76
+
77
+ offs_m = m_start + tile_m_idx * BLOCK_SIZE_M + tl.arange(0, BLOCK_SIZE_M)
78
+ x_ptrs = x_ptr + stride_xm * offs_m[:, None] + stride_xk * offs_k[None, :]
79
+ mask_m = offs_m < m_end
80
+
81
+ offs_n = tile_n_idx * BLOCK_SIZE_N + tl.arange(0, BLOCK_SIZE_N)
82
+ w_ptrs = w_ptr + stride_we * expert_idx + stride_wn * offs_n[:, None] + stride_wk * offs_k[None, :]
83
+ mask_n = offs_n < N
84
+
85
+ accumulator = tl.zeros((BLOCK_SIZE_M, BLOCK_SIZE_N), dtype=tl.float32)
86
+ # GEMM main loop
87
+ for _ in range(tl.cdiv(K, BLOCK_SIZE_K)):
88
+ mask_k = offs_k < K
89
+ x = tl.load(x_ptrs, mask=mask_m[:, None] & mask_k[None, :])
90
+ w = tl.load(w_ptrs, mask=mask_n[:, None] & mask_k[None, :])
91
+
92
+ accumulator += tl.dot(x.to(w.dtype), w.T)
93
+
94
+ offs_k += BLOCK_SIZE_K
95
+ x_ptrs += stride_xk * BLOCK_SIZE_K
96
+ w_ptrs += stride_wk * BLOCK_SIZE_K
97
+ y = accumulator.to(y_ptr.dtype.element_ty)
98
+
99
+ y_ptrs = y_ptr + stride_ym * offs_m[:, None] + stride_yn * offs_n[None, :]
100
+ tl.store(y_ptrs, y, mask=mask_m[:, None] & mask_n[None, :])
101
+
102
+ # Move to the next tile within this expert group
103
+ tidx += NUM_SMS
104
+
105
+ # Update the total tiles count for the next expert group
106
+ processed_tiles += num_tiles_per_expert
107
+
108
+
109
+ def is_int_tensor(x: torch.Tensor) -> bool:
110
+ return x.dtype in {
111
+ torch.uint8,
112
+ torch.int8,
113
+ torch.int16,
114
+ torch.int32,
115
+ torch.int64,
116
+ }
117
+
118
+
119
+ def grouped_gemm_forward(
120
+ x: torch.Tensor, w: torch.Tensor, m_sizes: torch.Tensor, dtype: Optional[torch.dtype] = None
121
+ ) -> torch.Tensor:
122
+ assert x.is_cuda
123
+ assert w.device == x.device
124
+ assert m_sizes.device == x.device
125
+ assert is_int_tensor(m_sizes)
126
+ assert x.is_contiguous()
127
+ assert w.is_contiguous()
128
+ assert m_sizes.is_contiguous()
129
+ assert x.ndim == 2
130
+ assert w.ndim == 3
131
+ assert m_sizes.ndim == 1
132
+ M, K = x.shape
133
+ E, N, _ = w.shape
134
+ assert w.shape[2] == K
135
+ assert m_sizes.numel() == E
136
+
137
+ if dtype is None:
138
+ dtype = x.dtype
139
+ y = torch.empty((M, N), device=x.device, dtype=dtype)
140
+ NUM_SMS = get_num_sms()
141
+ grid = lambda META: (NUM_SMS,)
142
+ with torch.cuda.device(x.device):
143
+ _grouped_gemm_forward_kernel[grid](
144
+ # Pointers
145
+ x,
146
+ w,
147
+ m_sizes,
148
+ y,
149
+ # Dimensions
150
+ M,
151
+ N,
152
+ K,
153
+ E,
154
+ NUM_SMS,
155
+ # Strides
156
+ x.stride(0),
157
+ x.stride(1),
158
+ w.stride(0),
159
+ w.stride(1),
160
+ w.stride(2),
161
+ y.stride(0),
162
+ y.stride(1),
163
+ )
164
+ return y
moondream3_moe_fused/grouped_gemm/forward_4bit.py ADDED
@@ -0,0 +1,209 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # y[m, n] = sum_k w[s[m], n, k] * x[m, k]
2
+ # Currently this is slower than the unfused dequant + linear when M is large
3
+
4
+ from typing import Optional
5
+
6
+ import torch
7
+ import triton
8
+ import triton.language as tl
9
+ from bitsandbytes.functional import QuantState, dequantize_blockwise
10
+
11
+ from .autotuning import (
12
+ get_autotune_configs,
13
+ get_autotune_keys,
14
+ get_num_sms,
15
+ prune_configs,
16
+ )
17
+
18
+
19
+ @triton.autotune(
20
+ configs=get_autotune_configs(),
21
+ prune_configs_by={"early_config_prune": prune_configs},
22
+ key=get_autotune_keys(),
23
+ )
24
+ @triton.jit
25
+ def _grouped_gemm_forward_4bit_kernel(
26
+ # Pointers
27
+ x_ptr,
28
+ w_quant_ptr,
29
+ w_code_ptr,
30
+ w_absmax_ptr,
31
+ w_blocksize: tl.constexpr,
32
+ m_sizes_ptr,
33
+ y_ptr,
34
+ # Dimensions
35
+ M: int,
36
+ N: tl.constexpr,
37
+ K: tl.constexpr,
38
+ NUM_EXPERTS: tl.constexpr,
39
+ NUM_SMS: tl.constexpr,
40
+ # Strides
41
+ stride_xm: tl.constexpr,
42
+ stride_xk: tl.constexpr,
43
+ stride_we: tl.constexpr,
44
+ stride_wn: tl.constexpr,
45
+ stride_wk: tl.constexpr,
46
+ stride_ym: tl.constexpr,
47
+ stride_yn: tl.constexpr,
48
+ # Metadata
49
+ BLOCK_SIZE_M: tl.constexpr = 64,
50
+ BLOCK_SIZE_N: tl.constexpr = 64,
51
+ BLOCK_SIZE_K: tl.constexpr = 64,
52
+ ) -> None:
53
+ tidx = tl.program_id(0)
54
+ m_end = 0
55
+ processed_tiles = 0
56
+ for expert_idx in range(NUM_EXPERTS):
57
+ m_start = m_end
58
+ m_size = tl.load(m_sizes_ptr + expert_idx).to(tl.int32)
59
+ m_end = m_start + m_size
60
+ if m_size > 0:
61
+ # tiles for this group's GEMM
62
+ num_m_tiles = tl.cdiv(m_size, BLOCK_SIZE_M)
63
+ num_n_tiles = tl.cdiv(N, BLOCK_SIZE_N)
64
+ num_tiles_per_expert = num_m_tiles * num_n_tiles
65
+
66
+ # Lower bound and upper bound are defined relative to the total tiles processed so far
67
+ # This ensures that we are only processing tiles for the current expert group AND
68
+ # we never exceed the total number of tiles for all expert groups
69
+ while tidx >= processed_tiles and tidx < processed_tiles + num_tiles_per_expert:
70
+ tile_idx = tidx - processed_tiles
71
+
72
+ # Output tile for this thread block for this expert group
73
+ # TODO: Check if L2 cache re-use for this order is optimal
74
+ tile_m_idx = tile_idx % num_m_tiles
75
+ tile_n_idx = tile_idx // num_m_tiles
76
+
77
+ offs_k = tl.arange(0, BLOCK_SIZE_K)
78
+ offs_k_d2 = tl.arange(0, BLOCK_SIZE_K // 2)
79
+
80
+ offs_m = m_start + tile_m_idx * BLOCK_SIZE_M + tl.arange(0, BLOCK_SIZE_M)
81
+ x_ptrs = x_ptr + stride_xm * offs_m[:, None] + stride_xk * offs_k[None, :]
82
+ mask_m = offs_m < m_end
83
+
84
+ offs_n = tile_n_idx * BLOCK_SIZE_N + tl.arange(0, BLOCK_SIZE_N)
85
+ w_offs = stride_we * expert_idx + stride_wn * offs_n[:, None] + stride_wk * offs_k[None, :]
86
+ w_offs_d2 = (
87
+ stride_we // 2 * expert_idx + stride_wn // 2 * offs_n[:, None] + stride_wk * offs_k_d2[None, :]
88
+ )
89
+ mask_n = offs_n < N
90
+
91
+ accumulator = tl.zeros((BLOCK_SIZE_M, BLOCK_SIZE_N), dtype=tl.float32)
92
+ # GEMM main loop
93
+ for _ in range(tl.cdiv(K, BLOCK_SIZE_K)):
94
+ mask_k = offs_k < K
95
+ mask_k_d2 = offs_k_d2 < K // 2
96
+ x = tl.load(x_ptrs, mask=mask_m[:, None] & mask_k[None, :])
97
+
98
+ # Dequantize
99
+ w_code_offs = tl.load(w_quant_ptr + w_offs_d2, mask=mask_n[:, None] & mask_k_d2[None, :])
100
+ w_code_offs = tl.interleave(w_code_offs // 16, w_code_offs % 16)
101
+ w_code = tl.load(w_code_ptr + w_code_offs, mask=mask_n[:, None] & mask_k[None, :])
102
+ w_absmax = tl.load(w_absmax_ptr + w_offs // w_blocksize)
103
+ # w_quant_state.dtype is ignored, and w is always cast to x.dtype
104
+ w = (w_code * w_absmax).to(x.dtype)
105
+
106
+ accumulator += tl.dot(x, w.T)
107
+
108
+ offs_k += BLOCK_SIZE_K
109
+ offs_k_d2 += BLOCK_SIZE_K // 2
110
+ x_ptrs += stride_xk * BLOCK_SIZE_K
111
+ w_offs += stride_wk * BLOCK_SIZE_K
112
+ w_offs_d2 += stride_wk * BLOCK_SIZE_K // 2
113
+ y = accumulator.to(y_ptr.dtype.element_ty)
114
+
115
+ y_ptrs = y_ptr + stride_ym * offs_m[:, None] + stride_yn * offs_n[None, :]
116
+ tl.store(y_ptrs, y, mask=mask_m[:, None] & mask_n[None, :])
117
+
118
+ # Move to the next tile within this expert group
119
+ tidx += NUM_SMS
120
+
121
+ # Update the total tiles count for the next expert group
122
+ processed_tiles += num_tiles_per_expert
123
+
124
+
125
+ def is_int_tensor(x: torch.Tensor) -> bool:
126
+ return x.dtype in {
127
+ torch.uint8,
128
+ torch.int8,
129
+ torch.int16,
130
+ torch.int32,
131
+ torch.int64,
132
+ }
133
+
134
+
135
+ def grouped_gemm_forward_4bit(
136
+ x: torch.Tensor,
137
+ w_quant: torch.Tensor,
138
+ w_quant_state: QuantState,
139
+ m_sizes: torch.Tensor,
140
+ dtype: Optional[torch.dtype] = None,
141
+ ) -> torch.Tensor:
142
+ assert w_quant_state.quant_type == "nf4"
143
+ assert w_quant_state.blocksize == triton.next_power_of_2(w_quant_state.blocksize)
144
+
145
+ # code and absmax should be float32. After computing code * absmax, w may be cast to bfloat16
146
+ w_code = w_quant_state.code
147
+ assert w_code.dtype == torch.float32
148
+
149
+ w_absmax = w_quant_state.absmax
150
+ if w_quant_state.nested:
151
+ w_absmax = dequantize_blockwise(w_absmax, w_quant_state.state2)
152
+ w_absmax += w_quant_state.offset
153
+ assert w_absmax.dtype == torch.float32
154
+
155
+ assert x.is_cuda
156
+ assert w_quant.device == x.device
157
+ assert w_code.device == x.device
158
+ assert w_absmax.device == x.device
159
+ assert m_sizes.device == x.device
160
+ assert is_int_tensor(w_quant)
161
+ assert is_int_tensor(m_sizes)
162
+ assert x.is_contiguous()
163
+ assert w_quant.is_contiguous()
164
+ assert w_code.is_contiguous()
165
+ assert w_absmax.is_contiguous()
166
+ assert m_sizes.is_contiguous()
167
+ assert x.ndim == 2
168
+ assert len(w_quant_state.shape) == 3
169
+ assert m_sizes.ndim == 1
170
+ M, K = x.shape
171
+ E, N, _ = w_quant_state.shape
172
+ assert w_quant_state.shape[2] == K
173
+ assert K % 2 == 0
174
+ assert E * N * K % w_quant_state.blocksize == 0
175
+ assert w_quant.numel() == E * N * K // 2
176
+ assert w_absmax.numel() == E * N * K // w_quant_state.blocksize
177
+ assert m_sizes.numel() == E
178
+
179
+ if dtype is None:
180
+ dtype = x.dtype
181
+ y = torch.empty((M, N), device=x.device, dtype=dtype)
182
+ NUM_SMS = get_num_sms()
183
+ grid = lambda META: (NUM_SMS,)
184
+ with torch.cuda.device(x.device):
185
+ _grouped_gemm_forward_4bit_kernel[grid](
186
+ # Pointers
187
+ x,
188
+ w_quant,
189
+ w_code,
190
+ w_absmax,
191
+ w_quant_state.blocksize,
192
+ m_sizes,
193
+ y,
194
+ # Dimensions
195
+ M,
196
+ N,
197
+ K,
198
+ E,
199
+ NUM_SMS,
200
+ # Strides
201
+ x.stride(0),
202
+ x.stride(1),
203
+ N * K,
204
+ K,
205
+ 1,
206
+ y.stride(0),
207
+ y.stride(1),
208
+ )
209
+ return y
moondream3_moe_fused/grouped_gemm/forward_transposed.py ADDED
@@ -0,0 +1,152 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # y[m, n] = sum_k w[s[m], k, n] * x[m, k]
2
+
3
+ from typing import Optional
4
+
5
+ import torch
6
+ import triton
7
+ import triton.language as tl
8
+
9
+ from .autotuning import (
10
+ get_autotune_configs,
11
+ get_autotune_keys,
12
+ get_num_sms,
13
+ prune_configs,
14
+ )
15
+ from .forward import is_int_tensor
16
+
17
+
18
+ @triton.autotune(
19
+ configs=get_autotune_configs(),
20
+ prune_configs_by={"early_config_prune": prune_configs},
21
+ key=get_autotune_keys(),
22
+ )
23
+ @triton.jit
24
+ def _grouped_gemm_forward_transposed_kernel(
25
+ # Pointers
26
+ x_ptr,
27
+ w_ptr,
28
+ m_sizes_ptr,
29
+ y_ptr,
30
+ # Dimensions
31
+ M: int,
32
+ N: tl.constexpr,
33
+ K: tl.constexpr,
34
+ NUM_EXPERTS: tl.constexpr,
35
+ NUM_SMS: tl.constexpr,
36
+ # Strides
37
+ stride_xm: tl.constexpr,
38
+ stride_xk: tl.constexpr,
39
+ stride_we: tl.constexpr,
40
+ stride_wk: tl.constexpr,
41
+ stride_wn: tl.constexpr,
42
+ stride_ym: tl.constexpr,
43
+ stride_yn: tl.constexpr,
44
+ # Metadata
45
+ BLOCK_SIZE_M: tl.constexpr = 64,
46
+ BLOCK_SIZE_N: tl.constexpr = 64,
47
+ BLOCK_SIZE_K: tl.constexpr = 64,
48
+ ) -> None:
49
+ tidx = tl.program_id(0)
50
+ m_end = 0
51
+ processed_tiles = 0
52
+ for expert_idx in range(NUM_EXPERTS):
53
+ m_start = m_end
54
+ m_size = tl.load(m_sizes_ptr + expert_idx).to(tl.int32)
55
+ m_end = m_start + m_size
56
+ if m_size > 0:
57
+ # tiles for this group's GEMM
58
+ num_m_tiles = tl.cdiv(m_size, BLOCK_SIZE_M)
59
+ num_n_tiles = tl.cdiv(N, BLOCK_SIZE_N)
60
+ num_tiles_per_expert = num_m_tiles * num_n_tiles
61
+
62
+ # Lower bound and upper bound are defined relative to the total tiles processed so far
63
+ # This ensures that we are only processing tiles for the current expert group AND
64
+ # we never exceed the total number of tiles for all expert groups
65
+ while tidx >= processed_tiles and tidx < processed_tiles + num_tiles_per_expert:
66
+ tile_idx = tidx - processed_tiles
67
+
68
+ # Output tile for this thread block for this expert group
69
+ # TODO: Check if L2 cache re-use for this order is optimal
70
+ tile_m_idx = tile_idx % num_m_tiles
71
+ tile_n_idx = tile_idx // num_m_tiles
72
+
73
+ offs_k = tl.arange(0, BLOCK_SIZE_K)
74
+
75
+ offs_m = m_start + tile_m_idx * BLOCK_SIZE_M + tl.arange(0, BLOCK_SIZE_M)
76
+ x_ptrs = x_ptr + stride_xm * offs_m[:, None] + stride_xk * offs_k[None, :]
77
+ mask_m = offs_m < m_start + m_size
78
+
79
+ offs_n = tile_n_idx * BLOCK_SIZE_N + tl.arange(0, BLOCK_SIZE_N)
80
+ w_ptrs = w_ptr + stride_we * expert_idx + stride_wn * offs_n[:, None] + stride_wk * offs_k[None, :]
81
+ mask_n = offs_n < N
82
+
83
+ accumulator = tl.zeros((BLOCK_SIZE_M, BLOCK_SIZE_N), dtype=tl.float32)
84
+ # GEMM main loop
85
+ for _ in range(tl.cdiv(K, BLOCK_SIZE_K)):
86
+ mask_k = offs_k < K
87
+ x = tl.load(x_ptrs, mask=mask_m[:, None] & mask_k[None, :])
88
+ w = tl.load(w_ptrs, mask=mask_n[:, None] & mask_k[None, :])
89
+
90
+ accumulator += tl.dot(x.to(w.dtype), w.T)
91
+
92
+ offs_k += BLOCK_SIZE_K
93
+ x_ptrs += stride_xk * BLOCK_SIZE_K
94
+ w_ptrs += stride_wk * BLOCK_SIZE_K
95
+ y = accumulator.to(y_ptr.dtype.element_ty)
96
+
97
+ y_ptrs = y_ptr + stride_ym * offs_m[:, None] + stride_yn * offs_n[None, :]
98
+ tl.store(y_ptrs, y, mask=mask_m[:, None] & mask_n[None, :])
99
+
100
+ # Move to the next tile within this expert group
101
+ tidx += NUM_SMS
102
+
103
+ # Update the total tiles count for the next expert group
104
+ processed_tiles += num_tiles_per_expert
105
+
106
+
107
+ def grouped_gemm_forward_transposed(
108
+ x: torch.Tensor, w: torch.Tensor, m_sizes: torch.Tensor, dtype: Optional[torch.dtype] = None
109
+ ) -> torch.Tensor:
110
+ assert x.is_cuda
111
+ assert w.device == x.device
112
+ assert m_sizes.device == x.device
113
+ assert is_int_tensor(m_sizes)
114
+ assert x.is_contiguous()
115
+ assert w.is_contiguous()
116
+ assert m_sizes.is_contiguous()
117
+ assert x.ndim == 2
118
+ assert w.ndim == 3
119
+ assert m_sizes.ndim == 1
120
+ M, K = x.shape
121
+ E, _, N = w.shape
122
+ assert w.shape[1] == K
123
+ assert m_sizes.numel() == E
124
+
125
+ if dtype is None:
126
+ dtype = x.dtype
127
+ y = torch.empty((M, N), device=x.device, dtype=dtype)
128
+ NUM_SMS = get_num_sms()
129
+ grid = lambda META: (NUM_SMS,)
130
+ with torch.cuda.device(x.device):
131
+ _grouped_gemm_forward_transposed_kernel[grid](
132
+ # Pointers
133
+ x,
134
+ w,
135
+ m_sizes,
136
+ y,
137
+ # Dimensions
138
+ M,
139
+ N,
140
+ K,
141
+ E,
142
+ NUM_SMS,
143
+ # Strides
144
+ x.stride(0),
145
+ x.stride(1),
146
+ w.stride(0),
147
+ w.stride(1),
148
+ w.stride(2),
149
+ y.stride(0),
150
+ y.stride(1),
151
+ )
152
+ return y
moondream3_moe_fused/grouped_gemm/interface.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+
3
+ from .backward_dw import grouped_gemm_backward_dw
4
+ from .forward import grouped_gemm_forward
5
+ from .forward_transposed import grouped_gemm_forward_transposed
6
+
7
+
8
+ class GroupedGemm(torch.autograd.Function):
9
+ @staticmethod
10
+ def forward(ctx, x, w, m_sizes):
11
+ ctx.save_for_backward(x, w, m_sizes)
12
+ return grouped_gemm_forward(x, w, m_sizes)
13
+
14
+ @staticmethod
15
+ def backward(ctx, dy):
16
+ x, w, m_sizes = ctx.saved_tensors
17
+
18
+ if x.requires_grad:
19
+ dx = grouped_gemm_forward_transposed(dy, w, m_sizes, x.dtype)
20
+ else:
21
+ dx = None
22
+
23
+ if w.requires_grad:
24
+ dw = grouped_gemm_backward_dw(x, dy, m_sizes, w.dtype)
25
+ else:
26
+ dw = None
27
+
28
+ return dx, dw, None
29
+
30
+
31
+ grouped_gemm = GroupedGemm.apply
moondream3_moe_fused/kernels/__init__.py ADDED
File without changes
moondream3_moe_fused/kernels/indexing.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from functools import partial
2
+
3
+ import torch
4
+
5
+
6
+ # Assume s is sorted
7
+ @partial(torch.compile, fullgraph=True, mode="max-autotune-no-cudagraphs")
8
+ @torch.no_grad()
9
+ def get_batch_begins_ends(s: torch.Tensor, E: int) -> torch.Tensor:
10
+ arange = torch.arange(E, device=s.device, dtype=s.dtype)
11
+ s_begins = (arange[:, None] > s[None, :]).sum(dim=1, dtype=torch.int32)
12
+ s_ends = (arange[:, None] >= s[None, :]).sum(dim=1, dtype=torch.int32)
13
+ s_begins_ends = torch.stack([s_begins, s_ends], dim=1)
14
+ return s_begins_ends
15
+
16
+
17
+ # Faster than torch.histc when each element of s is an int in [0, E)
18
+ @partial(torch.compile, fullgraph=True, mode="max-autotune-no-cudagraphs")
19
+ @torch.no_grad()
20
+ def get_expert_counts(s: torch.Tensor, E: int) -> torch.Tensor:
21
+ arange = torch.arange(E, device=s.device, dtype=s.dtype)
22
+ counts = (arange[:, None] == s[None, :]).sum(dim=1, dtype=torch.int32)
23
+ return counts
24
+
25
+
26
+ # Faster than torch.sort when each element of s is an int in [0, E)
27
+ @partial(torch.compile, fullgraph=True, mode="max-autotune-no-cudagraphs")
28
+ @torch.no_grad()
29
+ def sort_experts(s: torch.Tensor, E: int) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
30
+ E_arange = torch.arange(E, device=s.device, dtype=s.dtype)
31
+ compare = E_arange[:, None] == s[None, :]
32
+ counts = compare.sum(dim=1, dtype=torch.int32)
33
+ s_sorted = torch.repeat_interleave(counts, output_size=s.numel()) # int32
34
+
35
+ s_arange = torch.arange(s.numel(), device=s.device, dtype=s.dtype)
36
+ ranks_in_bin = compare.cumsum(dim=1, dtype=torch.int32)
37
+ ranks_in_bin = ranks_in_bin[s, s_arange]
38
+ offsets = counts.cumsum(dim=0, dtype=torch.int32) - counts
39
+ idx = ranks_in_bin + offsets[s] - 1 # int32
40
+
41
+ inv_idx = torch.empty_like(idx) # int32
42
+ inv_idx[idx] = s_arange.to(inv_idx.dtype)
43
+
44
+ # The above definition of idx is the opposite of torch.sort
45
+ return s_sorted, inv_idx, idx
46
+
47
+
48
+ @partial(torch.compile, fullgraph=True, mode="max-autotune-no-cudagraphs")
49
+ @torch.no_grad()
50
+ def get_expert_counts_and_idx(s: torch.Tensor, E: int) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
51
+ E_arange = torch.arange(E, device=s.device, dtype=s.dtype)
52
+ compare = E_arange[:, None] == s[None, :]
53
+ counts = compare.sum(dim=1, dtype=torch.int32)
54
+
55
+ s_arange = torch.arange(s.numel(), device=s.device, dtype=s.dtype)
56
+ ranks_in_bin = compare.cumsum(dim=1, dtype=torch.int32)
57
+ ranks_in_bin = ranks_in_bin[s, s_arange]
58
+ offsets = counts.cumsum(dim=0, dtype=torch.int32) - counts
59
+ idx = ranks_in_bin + offsets[s] - 1 # int32
60
+
61
+ inv_idx = torch.empty_like(idx) # int32
62
+ inv_idx[idx] = s_arange.to(inv_idx.dtype)
63
+
64
+ # The above definition of idx is the opposite of torch.sort
65
+ return counts, inv_idx, idx
moondream3_moe_fused/lora.py ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Modified from https://github.com/huggingface/peft/blob/e34852f7b67d51ba7ef871051b1236e9558c650e/src/peft/tuners/lora/layer.py#L585
2
+
3
+ import functools
4
+ import math
5
+ from typing import Optional, Union
6
+
7
+ import torch
8
+ from peft import LoraConfig
9
+ from peft.tuners.lora.layer import LoraLayer
10
+ from torch import nn
11
+
12
+ from .moe_fused_linear import MoeFusedLinear, moe_fused_kaiming_uniform_
13
+
14
+
15
+ class LoraMoeFusedLinear(nn.Module, LoraLayer):
16
+ def __init__(
17
+ self,
18
+ base_layer: MoeFusedLinear,
19
+ adapter_name: str,
20
+ r: int = 0,
21
+ lora_alpha: int = 1,
22
+ lora_dropout: float = 0.0,
23
+ init_lora_weights: Union[bool, str] = True,
24
+ use_rslora: bool = False,
25
+ use_dora: bool = False,
26
+ lora_bias: bool = False,
27
+ **kwargs,
28
+ ) -> None:
29
+ if init_lora_weights not in {True, False}:
30
+ raise NotImplementedError
31
+ if use_dora:
32
+ raise NotImplementedError
33
+ if lora_bias:
34
+ raise NotImplementedError
35
+
36
+ super().__init__()
37
+ LoraLayer.__init__(self, base_layer, **kwargs)
38
+ self.num_experts = base_layer.num_experts
39
+ self._active_adapter = adapter_name
40
+
41
+ self.update_layer(
42
+ adapter_name,
43
+ r,
44
+ lora_alpha=lora_alpha,
45
+ lora_dropout=lora_dropout,
46
+ init_lora_weights=init_lora_weights,
47
+ use_rslora=use_rslora,
48
+ )
49
+
50
+ def update_layer(
51
+ self,
52
+ adapter_name: str,
53
+ r: int,
54
+ lora_alpha: int,
55
+ lora_dropout: float,
56
+ init_lora_weights: Union[bool, str],
57
+ use_rslora: bool,
58
+ ) -> None:
59
+ # This code works for linear layers, override for other layer types
60
+ if r <= 0:
61
+ raise ValueError(f"`r` should be a positive integer value but the value passed is {r}")
62
+
63
+ self.r[adapter_name] = r
64
+ self.lora_alpha[adapter_name] = lora_alpha
65
+ if lora_dropout > 0.0:
66
+ lora_dropout_layer = nn.Dropout(p=lora_dropout)
67
+ else:
68
+ lora_dropout_layer = nn.Identity()
69
+ self.lora_dropout.update(nn.ModuleDict({adapter_name: lora_dropout_layer}))
70
+
71
+ # Actual trainable parameters
72
+ self.lora_A[adapter_name] = MoeFusedLinear(self.in_features, r, self.num_experts)
73
+ self.lora_B[adapter_name] = MoeFusedLinear(r, self.out_features, self.num_experts)
74
+
75
+ if use_rslora:
76
+ self.scaling[adapter_name] = lora_alpha / math.sqrt(r)
77
+ else:
78
+ self.scaling[adapter_name] = lora_alpha / r
79
+
80
+ if init_lora_weights is True:
81
+ self.reset_lora_parameters(adapter_name, init_lora_weights)
82
+
83
+ # call this before dora_init
84
+ self._move_adapter_to_device_of_base_layer(adapter_name)
85
+
86
+ self.set_adapter(self.active_adapters)
87
+
88
+ def reset_lora_parameters(self, adapter_name: str, init_lora_weights: Union[bool, str]) -> None:
89
+ if init_lora_weights is False:
90
+ return
91
+
92
+ if adapter_name in self.lora_A:
93
+ if init_lora_weights is True:
94
+ # initialize A the same way as the default for nn.Linear and B to zero
95
+ moe_fused_kaiming_uniform_(self.lora_A[adapter_name].weight)
96
+ nn.init.zeros_(self.lora_B[adapter_name].weight)
97
+ else:
98
+ raise ValueError(f"Unknown initialization {init_lora_weights=}")
99
+
100
+ def merge(self, safe_merge: bool = False, adapter_names: Optional[list[str]] = None) -> None:
101
+ raise NotImplementedError
102
+
103
+ def unmerge(self) -> None:
104
+ raise NotImplementedError
105
+
106
+ def forward(self, x: torch.Tensor, m_sizes: torch.Tensor, *args, **kwargs) -> torch.Tensor:
107
+ self._check_forward_args(x, *args, **kwargs)
108
+ adapter_names = kwargs.pop("adapter_names", None)
109
+
110
+ if self.disable_adapters:
111
+ if self.merged:
112
+ self.unmerge()
113
+ result = self.base_layer(x, m_sizes, *args, **kwargs)
114
+ elif adapter_names is not None:
115
+ raise NotImplementedError
116
+ # result = self._mixed_batch_forward(x, *args, adapter_names=adapter_names, **kwargs)
117
+ # In _mixed_batch_forward, we need to change `lora_B(lora_A(dropout(x)))`
118
+ # to `lora_B(lora_A(dropout(x), m_sizes), m_sizes)`
119
+ elif self.merged:
120
+ result = self.base_layer(x, m_sizes, *args, **kwargs)
121
+ else:
122
+ result = self.base_layer(x, m_sizes, *args, **kwargs)
123
+ torch_result_dtype = result.dtype
124
+
125
+ lora_A_keys = self.lora_A.keys()
126
+ for active_adapter in self.active_adapters:
127
+ if active_adapter not in lora_A_keys:
128
+ continue
129
+
130
+ lora_A = self.lora_A[active_adapter]
131
+ lora_B = self.lora_B[active_adapter]
132
+ dropout = self.lora_dropout[active_adapter]
133
+ scaling = self.scaling[active_adapter]
134
+ x = self._cast_input_dtype(x, lora_A.weight.dtype)
135
+ result = result + lora_B(lora_A(dropout(x), m_sizes), m_sizes) * scaling
136
+
137
+ result = result.to(torch_result_dtype)
138
+
139
+ return result
140
+
141
+ def __repr__(self) -> str:
142
+ rep = super().__repr__()
143
+ return "lora." + rep
moondream3_moe_fused/moe_fused_linear.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from torch import nn
3
+ import math
4
+ from typing import Optional
5
+ from .functional import moe_fused_linear
6
+
7
+ def moe_fused_kaiming_uniform_(weight: torch.Tensor) -> None:
8
+ # Kaiming uniform on in_features
9
+ # Although Qwen's default activation is silu, we set the gain `a = sqrt(5)` following the original Linear
10
+ in_features = weight.shape[-1]
11
+ bound = math.sqrt(3 * 5 / in_features)
12
+ nn.init.uniform_(weight, -bound, bound)
13
+
14
+ class MoeFusedLinear(nn.Module):
15
+ __constants__ = ["in_features", "out_features", "num_experts"]
16
+ in_features: int
17
+ out_features: int
18
+ num_experts: int
19
+ weight: torch.Tensor
20
+
21
+ def __init__(
22
+ self,
23
+ in_features: int,
24
+ out_features: int,
25
+ num_experts: int,
26
+ device: Optional[torch.device] = None,
27
+ dtype: Optional[torch.dtype] = None,
28
+ ) -> None:
29
+ factory_kwargs = {"device": device, "dtype": dtype}
30
+ super().__init__()
31
+ self.in_features = in_features
32
+ self.out_features = out_features
33
+ self.num_experts = num_experts
34
+ self.weight = nn.Parameter(torch.empty((num_experts, out_features, in_features), **factory_kwargs))
35
+ self.reset_parameters()
36
+
37
+ def reset_parameters(self) -> None:
38
+ moe_fused_kaiming_uniform_(self.weight)
39
+
40
+ def forward(self, input: torch.Tensor, m_sizes: torch.Tensor) -> torch.Tensor:
41
+ return moe_fused_linear(input, self.weight, m_sizes)
42
+
43
+ def extra_repr(self) -> str:
44
+ return f"in_features={self.in_features}, out_features={self.out_features}, num_experts={self.num_experts}"
moondream3_moe_fused/quantize/layer.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Modified from https://github.com/bitsandbytes-foundation/bitsandbytes/blob/888788d75db8ff8e8888838307119f98d1235c24/bitsandbytes/nn/modules.py#L377
2
+ # TODO: support IPEX
3
+
4
+ import warnings
5
+ from typing import Any, Optional
6
+
7
+ import torch
8
+ from bitsandbytes.functional import dequantize_4bit
9
+ from bitsandbytes.nn.modules import Params4bit, fix_4bit_weight_quant_state_from_module
10
+ from torch import nn
11
+
12
+ from ..functional import moe_fused_linear
13
+ from ..moe_fused_linear import MoeFusedLinear
14
+
15
+
16
+ # TODO: Fuse this
17
+ def moe_fused_linear_4bit(input: torch.Tensor, weight: Params4bit, m_sizes: torch.Tensor) -> torch.Tensor:
18
+ assert not weight.requires_grad
19
+ # Cast weight to input.dtype
20
+ # The grouped GEMM kernels use float32 accumulator
21
+ weight = dequantize_4bit(weight, weight.quant_state).to(input.dtype)
22
+ return moe_fused_linear(input, weight, m_sizes)
23
+
24
+
25
+ class MoeFusedLinear4bit(MoeFusedLinear):
26
+ def __init__(
27
+ self,
28
+ in_features: int,
29
+ out_features: int,
30
+ num_experts: int,
31
+ *,
32
+ weight: Optional[nn.Parameter] = None, # Used for initializing from a non-quantized module
33
+ compute_dtype: Optional[torch.dtype] = None,
34
+ compress_statistics: bool = True,
35
+ quant_type: str = "fp4",
36
+ quant_storage: torch.dtype = torch.uint8,
37
+ device: Optional[torch.device] = None,
38
+ ) -> None:
39
+ super().__init__(in_features, out_features, num_experts, device=device)
40
+ self.weight = Params4bit(
41
+ self.weight,
42
+ requires_grad=False,
43
+ compress_statistics=compress_statistics,
44
+ quant_type=quant_type,
45
+ quant_storage=quant_storage,
46
+ module=self,
47
+ )
48
+ # self.persistent_buffers = [] # TODO consider as way to save quant state
49
+ self.compute_dtype = compute_dtype
50
+ self.compute_type_is_set = compute_dtype is not None
51
+ self.quant_state = None
52
+ self.quant_storage = quant_storage
53
+
54
+ def set_compute_type(self, x: torch.Tensor) -> None:
55
+ if x.dtype in [torch.float32, torch.bfloat16]:
56
+ # the input is in a dtype that is safe to compute in, we switch
57
+ # to this type for speed and stability
58
+ self.compute_dtype = x.dtype
59
+ elif x.dtype == torch.float16:
60
+ # we take the compoute dtype passed into the layer
61
+ if self.compute_dtype in [None, torch.float32] and (x.numel() == x.shape[-1]):
62
+ # single batch inference with input torch.float16 and compute_dtype float32 -> slow inference when it could be fast
63
+ # warn the user about this
64
+ warnings.warn(
65
+ "Input type into Linear4bit is torch.float16, but bnb_4bit_compute_dtype=torch.float32 (default). "
66
+ "This will lead to slow inference.",
67
+ )
68
+ warnings.filterwarnings("ignore", message=".*inference.")
69
+ if self.compute_dtype in [None, torch.float32] and (x.numel() != x.shape[-1]):
70
+ warnings.warn(
71
+ "Input type into Linear4bit is torch.float16, but bnb_4bit_compute_dtype=torch.float32 (default). "
72
+ "This will lead to slow inference or training speed.",
73
+ )
74
+ warnings.filterwarnings("ignore", message=".*inference or training")
75
+
76
+ def _save_to_state_dict(self, destination: dict[str, Any], prefix: str, keep_vars: bool) -> None:
77
+ super()._save_to_state_dict(destination, prefix, keep_vars)
78
+
79
+ if getattr(self.weight, "quant_state", None) is not None:
80
+ for k, v in self.weight.quant_state.as_dict(packed=True).items():
81
+ destination[prefix + "weight." + k] = v if keep_vars else v.detach()
82
+
83
+ def forward(self, x: torch.Tensor, m_sizes: torch.Tensor) -> torch.Tensor:
84
+ fix_4bit_weight_quant_state_from_module(self)
85
+
86
+ if not self.compute_type_is_set:
87
+ self.set_compute_type(x)
88
+ self.compute_type_is_set = True
89
+
90
+ inp_dtype = x.dtype
91
+ if self.compute_dtype is not None:
92
+ x = x.to(self.compute_dtype)
93
+
94
+ x = moe_fused_linear_4bit(x, self.weight, m_sizes)
95
+ x = x.to(inp_dtype)
96
+ return x
moondream3_moe_fused/quantize/quantizer.py ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from inspect import signature
2
+ from typing import Any, Optional, Union
3
+
4
+ from accelerate import init_empty_weights
5
+ from bitsandbytes.nn import Linear4bit
6
+ from torch import nn
7
+ from transformers import BitsAndBytesConfig
8
+ from transformers.modeling_utils import PreTrainedModel
9
+ from transformers.pytorch_utils import Conv1D
10
+ from transformers.quantizers.quantizer_bnb_4bit import Bnb4BitHfQuantizer
11
+ from transformers.utils import logging
12
+
13
+ from ..modular_qwen3_moe_fused import MoeFusedLinear
14
+ from .layer import MoeFusedLinear4bit
15
+
16
+
17
+ logger = logging.get_logger(__name__)
18
+
19
+
20
+ # Modified from https://github.com/huggingface/transformers/blob/508a7040556dc6b45f09174c662a9632284b2445/src/transformers/integrations/bitsandbytes.py#L150
21
+ def _replace_with_bnb_moe_fused_linear(
22
+ model: nn.Module,
23
+ modules_to_not_convert: list[str],
24
+ current_key_name: list[str],
25
+ quantization_config: BitsAndBytesConfig,
26
+ has_been_replaced: bool,
27
+ ) -> bool:
28
+ for name, module in model.named_children():
29
+ current_key_name.append(name)
30
+
31
+ if isinstance(module, (nn.Linear, Conv1D, MoeFusedLinear)) and name not in modules_to_not_convert:
32
+ # Check if the current key is not in the `modules_to_not_convert`
33
+ current_key_name_str = ".".join(current_key_name)
34
+ if not any(
35
+ (key + "." in current_key_name_str) or (key == current_key_name_str) for key in modules_to_not_convert
36
+ ):
37
+ num_experts = None
38
+ if isinstance(module, MoeFusedLinear):
39
+ in_features = module.in_features
40
+ out_features = module.out_features
41
+ num_experts = module.num_experts
42
+ elif isinstance(module, Conv1D):
43
+ in_features, out_features = module.weight.shape
44
+ else:
45
+ in_features = module.in_features
46
+ out_features = module.out_features
47
+
48
+ if isinstance(module, MoeFusedLinear):
49
+ model._modules[name] = MoeFusedLinear4bit(
50
+ in_features,
51
+ out_features,
52
+ num_experts,
53
+ compute_dtype=quantization_config.bnb_4bit_compute_dtype,
54
+ compress_statistics=quantization_config.bnb_4bit_use_double_quant,
55
+ quant_type=quantization_config.bnb_4bit_quant_type,
56
+ quant_storage=quantization_config.bnb_4bit_quant_storage,
57
+ )
58
+ else:
59
+ extra_kwargs = (
60
+ {"quant_storage": quantization_config.bnb_4bit_quant_storage}
61
+ if "quant_storage" in list(signature(Linear4bit).parameters)
62
+ else {}
63
+ )
64
+ model._modules[name] = Linear4bit(
65
+ in_features,
66
+ out_features,
67
+ module.bias is not None,
68
+ quantization_config.bnb_4bit_compute_dtype,
69
+ compress_statistics=quantization_config.bnb_4bit_use_double_quant,
70
+ quant_type=quantization_config.bnb_4bit_quant_type,
71
+ **extra_kwargs,
72
+ )
73
+
74
+ has_been_replaced = True
75
+ # Store the module class in case we need to transpose the weight later
76
+ model._modules[name].source_cls = type(module)
77
+ # Force requires grad to False to avoid unexpected errors
78
+ model._modules[name].requires_grad_(False)
79
+
80
+ if len(list(module.children())) > 0:
81
+ has_been_replaced = _replace_with_bnb_moe_fused_linear(
82
+ module, modules_to_not_convert, current_key_name, quantization_config, has_been_replaced
83
+ )
84
+
85
+ # Remove the last key for recursion
86
+ current_key_name.pop(-1)
87
+
88
+ return has_been_replaced
89
+
90
+
91
+ # model is modified in place
92
+ def replace_with_bnb_moe_fused_linear(
93
+ model: nn.Module, modules_to_not_convert: Optional[list[str]], quantization_config: BitsAndBytesConfig
94
+ ) -> None:
95
+ modules_to_not_convert = ["lm_head"] if modules_to_not_convert is None else modules_to_not_convert
96
+ with init_empty_weights():
97
+ has_been_replaced = _replace_with_bnb_moe_fused_linear(
98
+ model, modules_to_not_convert, [], quantization_config, False
99
+ )
100
+
101
+ if not has_been_replaced:
102
+ logger.warning(
103
+ "You are loading your model in 8bit or 4bit but no linear modules were found in your model."
104
+ " Please double check your model architecture, or submit an issue on github if you think this is"
105
+ " a bug."
106
+ )
107
+
108
+
109
+ def _process_model_before_weight_loading(
110
+ self: Bnb4BitHfQuantizer,
111
+ model: PreTrainedModel,
112
+ device_map: Union[str, dict[str, Any]],
113
+ keep_in_fp32_modules: Optional[list[str]] = None,
114
+ **kwargs,
115
+ ) -> None:
116
+ self.modules_to_not_convert = self.get_modules_to_not_convert(
117
+ model, self.quantization_config.llm_int8_skip_modules, keep_in_fp32_modules
118
+ )
119
+
120
+ # Extend `self.modules_to_not_convert` to keys that are supposed to be offloaded to `cpu` or `disk`
121
+ if isinstance(device_map, dict) and len(device_map) > 1:
122
+ keys_on_cpu = [key for key, value in device_map.items() if value in ["disk", "cpu"]]
123
+ self.modules_to_not_convert.extend(keys_on_cpu)
124
+
125
+ replace_with_bnb_moe_fused_linear(
126
+ model, modules_to_not_convert=self.modules_to_not_convert, quantization_config=self.quantization_config
127
+ )
128
+
129
+ model.config.quantization_config = self.quantization_config
130
+
131
+
132
+ def patch_bnb_quantizer() -> None:
133
+ Bnb4BitHfQuantizer._process_model_before_weight_loading = _process_model_before_weight_loading
preprocessor_config.json ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "auto_map": {
3
+ "AutoImageProcessor": "image_processing_moondream3.Moondream3ImageProcessor",
4
+ "AutoProcessor": "processing_moondream3.Moondream3Processor"
5
+ },
6
+ "image_processor_type": "Moondream3ImageProcessor",
7
+ "max_crops": 12,
8
+ "overlap_margin": 4,
9
+ "processor_class": "Moondream3Processor"
10
+ }
processing_moondream3.py ADDED
@@ -0,0 +1,256 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 The HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """
16
+ Processor class for Moondream3.
17
+ """
18
+
19
+ from typing import Optional, Union
20
+
21
+ import numpy as np
22
+
23
+ from transformers.feature_extraction_utils import BatchFeature
24
+ from transformers.image_utils import ImageInput, is_valid_image
25
+ from transformers.processing_utils import (
26
+ MultiModalData,
27
+ ProcessingKwargs,
28
+ ProcessorMixin,
29
+ Unpack,
30
+ )
31
+ from transformers.tokenization_utils_base import PreTokenizedInput, TextInput
32
+ from transformers.utils import is_vision_available, logging
33
+
34
+
35
+ logger = logging.get_logger(__name__)
36
+
37
+
38
+ class Moondream3ProcessorKwargs(ProcessingKwargs, total=False):
39
+ _defaults = {
40
+ "text_kwargs": {
41
+ "padding": False,
42
+ "return_token_type_ids": False
43
+ },
44
+ "common_kwargs": {
45
+ "return_tensors": "pt",
46
+ },
47
+ }
48
+
49
+ def _rotate_right_array(x, k: int):
50
+ """
51
+ Rotate a 1D or 2D structure k steps to the right along the last axis.
52
+ Supports: list, numpy.ndarray, torch.Tensor.
53
+ Works even if numpy or torch are not installed.
54
+ Raises TypeError for unsupported input types.
55
+ """
56
+ # optional imports
57
+ try:
58
+ import numpy as np
59
+ except ImportError:
60
+ np = None
61
+
62
+ try:
63
+ import torch
64
+ except ImportError:
65
+ torch = None
66
+
67
+ # torch.Tensor
68
+ if torch is not None and isinstance(x, torch.Tensor):
69
+ if x.size(-1) == 0:
70
+ return x
71
+ return torch.roll(x, shifts=k % x.size(-1), dims=-1)
72
+
73
+ # numpy.ndarray
74
+ if np is not None and isinstance(x, np.ndarray):
75
+ if x.shape[-1] == 0:
76
+ return x
77
+ return np.roll(x, k % x.shape[-1], axis=-1)
78
+
79
+ # python list (1D or 2D)
80
+ if isinstance(x, list):
81
+ if not x: # empty list
82
+ return x
83
+ # 2D (batch, seq)
84
+ if isinstance(x[0], list):
85
+ out = []
86
+ for row in x:
87
+ if not row:
88
+ out.append(row)
89
+ continue
90
+ shift = k % len(row)
91
+ out.append(row[-shift:] + row[:-shift] if shift else row[:])
92
+ return out
93
+ # 1D
94
+ shift = k % len(x)
95
+ return x[-shift:] + x[:-shift] if shift else x[:]
96
+
97
+ # unsupported type
98
+ raise TypeError(
99
+ f"Unsupported type {type(x).__name__} for rotation. "
100
+ f"Expected list, numpy.ndarray, or torch.Tensor. "
101
+ f"(numpy or torch are optional dependencies)"
102
+ )
103
+
104
+
105
+ # Copied from transformers.models.idefics2.processing_idefics2.is_url
106
+ def is_url(val) -> bool:
107
+ return isinstance(val, str) and val.startswith("http")
108
+
109
+
110
+ # Copied from transformers.models.idefics2.processing_idefics2.is_image_or_image_url
111
+ def is_image_or_image_url(elem):
112
+ return is_url(elem) or is_valid_image(elem)
113
+
114
+
115
+ class Moondream3Processor(ProcessorMixin):
116
+ r"""
117
+ Constructs a Moondream3 processor which wraps a Moondream3 image processor and a Moondream3 tokenizer into a single processor.
118
+
119
+ [`Moondream3Processor`] offers all the functionalities of [`CLIPImageProcessor`] and [`LlamaTokenizerFast`]. See the
120
+ [`~Moondream3Processor.__call__`] and [`~Moondream3Processor.decode`] for more information.
121
+
122
+ Args:
123
+ image_processor ([`Moondream3ImageProcessor`], *optional*):
124
+ The image processor is a required input.
125
+ tokenizer ([`LlamaTokenizerFast`], *optional*):
126
+ The tokenizer is a required input.
127
+ patch_size (`int`, *optional*, defaults to 16):
128
+ Patch size from the vision tower.
129
+ spatial_merge_size (`int`, *optional*, defaults to 1):
130
+ The downsampling factor for the spatial merge operation.
131
+ chat_template (`str`, *optional*): A Jinja template which will be used to convert lists of messages
132
+ in a chat into a tokenizable string.
133
+ image_token (`str`, *optional*, defaults to `"[IMG]"`):
134
+ Special token used to denote image location.
135
+ image_break_token (`str`, *optional*, defaults to `"[IMG_BREAK]"`):
136
+ Special token used to denote the end of a line of pixels in an image.
137
+ image_end_token (`str`, *optional*, defaults to `"[IMG_END]"`):
138
+ Special token used to denote the end of an image input.
139
+ """
140
+
141
+ attributes = ["image_processor", "tokenizer"]
142
+ image_processor_class = "AutoImageProcessor"
143
+ tokenizer_class = "AutoTokenizer"
144
+
145
+ def __init__(
146
+ self,
147
+ image_processor=None,
148
+ tokenizer=None,
149
+ chat_template=None,
150
+ image_token_id=0,
151
+ **kwargs,
152
+ ):
153
+ self.image_token_id = image_token_id
154
+ super().__init__(image_processor, tokenizer, chat_template=chat_template)
155
+
156
+ def __call__(
157
+ self,
158
+ images: Optional[ImageInput] = None,
159
+ text: Union[TextInput, PreTokenizedInput, list[TextInput], list[PreTokenizedInput]] = None,
160
+ **kwargs: Unpack[Moondream3ProcessorKwargs],
161
+ ) -> BatchFeature:
162
+ """
163
+ Main method to prepare for the model one or several sequences(s) and image(s). This method forwards the `text`
164
+ and `kwargs` arguments to LlamaTokenizerFast's [`~LlamaTokenizerFast.__call__`] if `text` is not `None` to encode
165
+ the text. To prepare the image(s), this method forwards the `images` and `kwargs` arguments to
166
+ CLIPImageProcessor's [`~CLIPImageProcessor.__call__`] if `images` is not `None`. Please refer to the docstring
167
+ of the above two methods for more information.
168
+
169
+ Args:
170
+ images (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `list[PIL.Image.Image]`, `list[np.ndarray]`, `list[torch.Tensor]`):
171
+ The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch
172
+ tensor. Both channels-first and channels-last formats are supported.
173
+ text (`str`, `list[str]`, `list[list[str]]`):
174
+ The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings
175
+ (pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set
176
+ `is_split_into_words=True` (to lift the ambiguity with a batch of sequences).
177
+ return_tensors (`str` or [`~utils.TensorType`], *optional*):
178
+ If set, will return tensors of a particular framework. Acceptable values are:
179
+
180
+ - `'pt'`: Return PyTorch `torch.Tensor` objects.
181
+ - `'np'`: Return NumPy `np.ndarray` objects.
182
+
183
+ Returns:
184
+ [`BatchFeature`]: A [`BatchFeature`] with the following fields:
185
+
186
+ - **input_ids** -- List of token ids to be fed to a model. Returned when `text` is not `None`.
187
+ - **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
188
+ `return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
189
+ `None`).
190
+ - **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`.
191
+ """
192
+
193
+ output_kwargs = self._merge_kwargs(
194
+ Moondream3ProcessorKwargs,
195
+ tokenizer_init_kwargs=self.tokenizer.init_kwargs,
196
+ **kwargs,
197
+ )
198
+
199
+ if images is not None:
200
+ image_inputs = self.image_processor(images, **output_kwargs["images_kwargs"])
201
+ else:
202
+ image_inputs = {}
203
+
204
+ if isinstance(text, str):
205
+ text = [text]
206
+ elif not isinstance(text, list) and not isinstance(text[0], str):
207
+ raise TypeError("Invalid input text. Please provide a string, or a list of strings")
208
+
209
+ # try to expand inputs in processing if we have the necessary parts
210
+ prompt_strings = text
211
+
212
+ return_tensors = output_kwargs["text_kwargs"].pop("return_tensors", None)
213
+ text_inputs = self.tokenizer(prompt_strings, **output_kwargs["text_kwargs"], return_tensors=None)
214
+ if "input_ids" in text_inputs:
215
+ # prepend 1 bos_token_id and 729 image_token_id to the text_inputs
216
+ for i in range(len(text_inputs["input_ids"])):
217
+ prepended_tokens = [self.tokenizer.bos_token_id] + [self.image_token_id] * 729
218
+ text_inputs["input_ids"][i] = prepended_tokens + text_inputs["input_ids"][i]
219
+ if "attention_mask" in text_inputs:
220
+ # attend to the 730 prepended tokens
221
+ for i in range(len(text_inputs["attention_mask"])):
222
+ prepended_mask = [1] * 730
223
+ text_inputs["attention_mask"][i] = prepended_mask + text_inputs["attention_mask"][i]
224
+
225
+ return BatchFeature(data={**text_inputs, **image_inputs}, tensor_type=return_tensors)
226
+
227
+ def apply_chat_template(
228
+ self,
229
+ conversation: Union[list[dict[str, str]], list[list[dict[str, str]]]],
230
+ chat_template: Optional[str] = None,
231
+ **kwargs,
232
+ ) -> str:
233
+ # Call the original behavior first
234
+ out = super().apply_chat_template(
235
+ conversation=conversation,
236
+ chat_template=chat_template,
237
+ **kwargs,
238
+ )
239
+
240
+ # Only post-process when:
241
+ # - user requested assistant mask
242
+ # - output is a dict (tokenized + return_dict=True path)
243
+ if isinstance(out, BatchFeature) and kwargs.get("return_assistant_tokens_mask", False):
244
+ if "assistant_masks" in out and out["assistant_masks"] is not None:
245
+ out["assistant_masks"] = _rotate_right_array(out["assistant_masks"], 730)
246
+
247
+ return out
248
+
249
+ @property
250
+ def model_input_names(self):
251
+ tokenizer_input_names = self.tokenizer.model_input_names
252
+ image_processor_input_names = self.image_processor.model_input_names
253
+ return tokenizer_input_names + image_processor_input_names + ["image_sizes"]
254
+
255
+
256
+ __all__ = ["Moondream3Processor"]
processor_config.json ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ {
2
+ "auto_map": {
3
+ "AutoProcessor": "processing_moondream3.Moondream3Processor"
4
+ },
5
+ "image_token_id": 0,
6
+ "processor_class": "Moondream3Processor"
7
+ }
special_tokens_map.json ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token": {
3
+ "content": "<|endoftext|>",
4
+ "lstrip": false,
5
+ "normalized": false,
6
+ "rstrip": false,
7
+ "single_word": false,
8
+ "special": true
9
+ }
10
+ }
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer_config.json ADDED
@@ -0,0 +1,180 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "added_tokens_decoder": {
3
+ "0": {
4
+ "content": "<|endoftext|>",
5
+ "lstrip": false,
6
+ "normalized": false,
7
+ "rstrip": false,
8
+ "single_word": false,
9
+ "special": true
10
+ },
11
+ "1": {
12
+ "content": "<|md_reserved_0|>",
13
+ "lstrip": false,
14
+ "normalized": false,
15
+ "rstrip": false,
16
+ "single_word": false,
17
+ "special": true
18
+ },
19
+ "2": {
20
+ "content": "<|md_reserved_1|>",
21
+ "lstrip": false,
22
+ "normalized": false,
23
+ "rstrip": false,
24
+ "single_word": false,
25
+ "special": true
26
+ },
27
+ "3": {
28
+ "content": "<|md_reserved_2|>",
29
+ "lstrip": false,
30
+ "normalized": false,
31
+ "rstrip": false,
32
+ "single_word": false,
33
+ "special": true
34
+ },
35
+ "4": {
36
+ "content": "<|md_reserved_3|>",
37
+ "lstrip": false,
38
+ "normalized": false,
39
+ "rstrip": false,
40
+ "single_word": false,
41
+ "special": true
42
+ },
43
+ "5": {
44
+ "content": "<|md_reserved_4|>",
45
+ "lstrip": false,
46
+ "normalized": false,
47
+ "rstrip": false,
48
+ "single_word": false,
49
+ "special": true
50
+ },
51
+ "6": {
52
+ "content": "<|md_reserved_5|>",
53
+ "lstrip": false,
54
+ "normalized": false,
55
+ "rstrip": false,
56
+ "single_word": false,
57
+ "special": true
58
+ },
59
+ "7": {
60
+ "content": "<|md_reserved_6|>",
61
+ "lstrip": false,
62
+ "normalized": false,
63
+ "rstrip": false,
64
+ "single_word": false,
65
+ "special": true
66
+ },
67
+ "8": {
68
+ "content": "<|md_reserved_7|>",
69
+ "lstrip": false,
70
+ "normalized": false,
71
+ "rstrip": false,
72
+ "single_word": false,
73
+ "special": true
74
+ },
75
+ "9": {
76
+ "content": "<|md_reserved_8|>",
77
+ "lstrip": false,
78
+ "normalized": false,
79
+ "rstrip": false,
80
+ "single_word": false,
81
+ "special": true
82
+ },
83
+ "10": {
84
+ "content": "<|md_reserved_9|>",
85
+ "lstrip": false,
86
+ "normalized": false,
87
+ "rstrip": false,
88
+ "single_word": false,
89
+ "special": true
90
+ },
91
+ "11": {
92
+ "content": "<|md_reserved_10|>",
93
+ "lstrip": false,
94
+ "normalized": false,
95
+ "rstrip": false,
96
+ "single_word": false,
97
+ "special": true
98
+ },
99
+ "12": {
100
+ "content": "<|md_reserved_11|>",
101
+ "lstrip": false,
102
+ "normalized": false,
103
+ "rstrip": false,
104
+ "single_word": false,
105
+ "special": true
106
+ },
107
+ "13": {
108
+ "content": "<|md_reserved_12|>",
109
+ "lstrip": false,
110
+ "normalized": false,
111
+ "rstrip": false,
112
+ "single_word": false,
113
+ "special": true
114
+ },
115
+ "14": {
116
+ "content": "<|md_reserved_13|>",
117
+ "lstrip": false,
118
+ "normalized": false,
119
+ "rstrip": false,
120
+ "single_word": false,
121
+ "special": true
122
+ },
123
+ "15": {
124
+ "content": "<|md_reserved_14|>",
125
+ "lstrip": false,
126
+ "normalized": false,
127
+ "rstrip": false,
128
+ "single_word": false,
129
+ "special": true
130
+ },
131
+ "16": {
132
+ "content": "<|md_reserved_15|>",
133
+ "lstrip": false,
134
+ "normalized": false,
135
+ "rstrip": false,
136
+ "single_word": false,
137
+ "special": true
138
+ },
139
+ "17": {
140
+ "content": "<|md_reserved_16|>",
141
+ "lstrip": false,
142
+ "normalized": false,
143
+ "rstrip": false,
144
+ "single_word": false,
145
+ "special": true
146
+ },
147
+ "18": {
148
+ "content": "<|md_reserved_17|>",
149
+ "lstrip": false,
150
+ "normalized": false,
151
+ "rstrip": false,
152
+ "single_word": false,
153
+ "special": true
154
+ },
155
+ "19": {
156
+ "content": "<|md_reserved_18|>",
157
+ "lstrip": false,
158
+ "normalized": false,
159
+ "rstrip": false,
160
+ "single_word": false,
161
+ "special": true
162
+ },
163
+ "20": {
164
+ "content": "<|md_reserved_19|>",
165
+ "lstrip": false,
166
+ "normalized": false,
167
+ "rstrip": false,
168
+ "single_word": false,
169
+ "special": true
170
+ }
171
+ },
172
+ "bos_token": "<|endoftext|>",
173
+ "eos_token": "<|endoftext|>",
174
+ "pad_token": "<|endoftext|>",
175
+ "clean_up_tokenization_spaces": false,
176
+ "extra_special_tokens": {},
177
+ "model_max_length": 1000000000000000019884624838656,
178
+ "processor_class": "Moondream3Processor",
179
+ "tokenizer_class": "PreTrainedTokenizerFast"
180
+ }