Mightys commited on
Commit
5d7514b
·
verified ·
1 Parent(s): 66c45a4

Upload 56 files

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. modules_forge/config.py +4 -0
  2. modules_forge/cuda_malloc.py +92 -0
  3. modules_forge/diffusers_patcher.py +49 -0
  4. modules_forge/forge_alter_samplers.py +50 -0
  5. modules_forge/forge_canvas/canvas.css +160 -0
  6. modules_forge/forge_canvas/canvas.html +58 -0
  7. modules_forge/forge_canvas/canvas.js +840 -0
  8. modules_forge/forge_canvas/canvas.py +138 -0
  9. modules_forge/forge_version.py +1 -0
  10. modules_forge/initialization.py +80 -0
  11. modules_forge/main_entry.py +343 -0
  12. modules_forge/main_thread.py +77 -0
  13. modules_forge/packages/comfy/LICENSE +674 -0
  14. modules_forge/packages/comfy/lora.py +232 -0
  15. modules_forge/packages/comfy/utils.py +336 -0
  16. modules_forge/packages/comfy/weight_adapter/__init__.py +39 -0
  17. modules_forge/packages/comfy/weight_adapter/base.py +165 -0
  18. modules_forge/packages/comfy/weight_adapter/boft.py +110 -0
  19. modules_forge/packages/comfy/weight_adapter/glora.py +95 -0
  20. modules_forge/packages/comfy/weight_adapter/loha.py +224 -0
  21. modules_forge/packages/comfy/weight_adapter/lokr.py +210 -0
  22. modules_forge/packages/comfy/weight_adapter/lora.py +198 -0
  23. modules_forge/packages/comfy/weight_adapter/oft.py +166 -0
  24. modules_forge/packages/comfy/weight_adapter/oftv2.py +196 -0
  25. modules_forge/packages/gguf/LICENSE +21 -0
  26. modules_forge/packages/gguf/README.md +3 -0
  27. modules_forge/packages/gguf/__init__.py +8 -0
  28. modules_forge/packages/gguf/constants.py +1362 -0
  29. modules_forge/packages/gguf/gguf_reader.py +333 -0
  30. modules_forge/packages/gguf/gguf_writer.py +975 -0
  31. modules_forge/packages/gguf/lazy.py +286 -0
  32. modules_forge/packages/gguf/metadata.py +653 -0
  33. modules_forge/packages/gguf/quants.py +1762 -0
  34. modules_forge/packages/gguf/quick_4bits_ops.py +95 -0
  35. modules_forge/packages/gguf/tensor_mapping.py +540 -0
  36. modules_forge/packages/gguf/utility.py +101 -0
  37. modules_forge/packages/huggingface_guess/LICENSE +621 -0
  38. modules_forge/packages/huggingface_guess/README.md +28 -0
  39. modules_forge/packages/huggingface_guess/__init__.py +38 -0
  40. modules_forge/packages/huggingface_guess/detection.py +560 -0
  41. modules_forge/packages/huggingface_guess/diffusers_convert.py +280 -0
  42. modules_forge/packages/huggingface_guess/latent.py +121 -0
  43. modules_forge/packages/huggingface_guess/model_list.py +466 -0
  44. modules_forge/packages/huggingface_guess/utils.py +482 -0
  45. modules_forge/packages/k_diffusion/deis.py +127 -0
  46. modules_forge/packages/k_diffusion/external.py +39 -0
  47. modules_forge/packages/k_diffusion/sampling.py +845 -0
  48. modules_forge/packages/k_diffusion/utils.py +447 -0
  49. modules_forge/patch_basic.py +96 -0
  50. modules_forge/presets.py +148 -0
modules_forge/config.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ always_disabled_extensions = [
2
+ 'sd-webui-controlnet',
3
+ 'multidiffusion-upscaler-for-automatic1111',
4
+ ]
modules_forge/cuda_malloc.py ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import importlib.util
3
+
4
+
5
+ # https://github.com/comfyanonymous/ComfyUI/blob/master/cuda_malloc.py
6
+ def get_gpu_names():
7
+ if os.name == 'nt':
8
+ import ctypes
9
+
10
+ # Define necessary C structures and types
11
+ class DISPLAY_DEVICEA(ctypes.Structure):
12
+ _fields_ = [
13
+ ('cb', ctypes.c_ulong),
14
+ ('DeviceName', ctypes.c_char * 32),
15
+ ('DeviceString', ctypes.c_char * 128),
16
+ ('StateFlags', ctypes.c_ulong),
17
+ ('DeviceID', ctypes.c_char * 128),
18
+ ('DeviceKey', ctypes.c_char * 128)
19
+ ]
20
+
21
+ # Load user32.dll
22
+ user32 = ctypes.windll.user32
23
+
24
+ # Call EnumDisplayDevicesA
25
+ def enum_display_devices():
26
+ device_info = DISPLAY_DEVICEA()
27
+ device_info.cb = ctypes.sizeof(device_info)
28
+ device_index = 0
29
+ gpu_names = set()
30
+
31
+ while user32.EnumDisplayDevicesA(None, device_index, ctypes.byref(device_info), 0):
32
+ device_index += 1
33
+ gpu_names.add(device_info.DeviceString.decode('utf-8'))
34
+ return gpu_names
35
+ return enum_display_devices()
36
+ else:
37
+ return set()
38
+
39
+
40
+ blacklist = {"GeForce GTX TITAN X", "GeForce GTX 980", "GeForce GTX 970", "GeForce GTX 960", "GeForce GTX 950", "GeForce 945M",
41
+ "GeForce 940M", "GeForce 930M", "GeForce 920M", "GeForce 910M", "GeForce GTX 750", "GeForce GTX 745", "Quadro K620",
42
+ "Quadro K1200", "Quadro K2200", "Quadro M500", "Quadro M520", "Quadro M600", "Quadro M620", "Quadro M1000",
43
+ "Quadro M1200", "Quadro M2000", "Quadro M2200", "Quadro M3000", "Quadro M4000", "Quadro M5000", "Quadro M5500", "Quadro M6000",
44
+ "GeForce MX110", "GeForce MX130", "GeForce 830M", "GeForce 840M", "GeForce GTX 850M", "GeForce GTX 860M",
45
+ "GeForce GTX 1650", "GeForce GTX 1630"
46
+ }
47
+
48
+
49
+ def cuda_malloc_supported():
50
+ try:
51
+ names = get_gpu_names()
52
+ except:
53
+ names = set()
54
+ for x in names:
55
+ if "NVIDIA" in x:
56
+ for b in blacklist:
57
+ if b in x:
58
+ return False
59
+ return True
60
+
61
+
62
+ def try_cuda_malloc():
63
+ do_cuda_malloc = False
64
+
65
+ try:
66
+ version = ""
67
+ torch_spec = importlib.util.find_spec("torch")
68
+ for folder in torch_spec.submodule_search_locations:
69
+ ver_file = os.path.join(folder, "version.py")
70
+ if os.path.isfile(ver_file):
71
+ spec = importlib.util.spec_from_file_location("torch_version_import", ver_file)
72
+ module = importlib.util.module_from_spec(spec)
73
+ spec.loader.exec_module(module)
74
+ version = module.__version__
75
+ if int(version[0]) >= 2:
76
+ do_cuda_malloc = cuda_malloc_supported()
77
+ except:
78
+ pass
79
+
80
+ if do_cuda_malloc:
81
+ env_var = os.environ.get('PYTORCH_CUDA_ALLOC_CONF', None)
82
+ if env_var is None:
83
+ env_var = "backend:cudaMallocAsync"
84
+ else:
85
+ env_var += ",backend:cudaMallocAsync"
86
+
87
+ os.environ['PYTORCH_CUDA_ALLOC_CONF'] = env_var
88
+
89
+ print('Using cudaMallocAsync backend.')
90
+ else:
91
+ print('Failed to use cudaMallocAsync backend.')
92
+ return
modules_forge/diffusers_patcher.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from backend import operations, memory_management
3
+ from backend.patcher.base import ModelPatcher
4
+
5
+ from transformers import modeling_utils
6
+
7
+
8
+ class DiffusersModelPatcher:
9
+ def __init__(self, pipeline_class, dtype=torch.float16, *args, **kwargs):
10
+ load_device = memory_management.get_torch_device()
11
+ offload_device = torch.device("cpu")
12
+
13
+ if not memory_management.should_use_fp16(device=load_device):
14
+ dtype = torch.float32
15
+
16
+ self.dtype = dtype
17
+
18
+ with operations.using_forge_operations():
19
+ with modeling_utils.no_init_weights():
20
+ self.pipeline = pipeline_class.from_pretrained(*args, **kwargs)
21
+
22
+ if hasattr(self.pipeline, 'unet'):
23
+ if hasattr(self.pipeline.unet, 'set_attn_processor'):
24
+ from diffusers.models.attention_processor import AttnProcessor2_0
25
+ self.pipeline.unet.set_attn_processor(AttnProcessor2_0())
26
+ print('Attention optimization applied to DiffusersModelPatcher')
27
+
28
+ self.pipeline = self.pipeline.to(device=offload_device)
29
+
30
+ if self.dtype == torch.float16:
31
+ self.pipeline = self.pipeline.half()
32
+
33
+ self.pipeline.eval()
34
+
35
+ self.patcher = ModelPatcher(
36
+ model=self.pipeline,
37
+ load_device=load_device,
38
+ offload_device=offload_device)
39
+
40
+ def prepare_memory_before_sampling(self, batchsize, latent_width, latent_height):
41
+ area = 2 * batchsize * latent_width * latent_height
42
+ inference_memory = (((area * 0.6) / 0.9) + 1024) * (1024 * 1024)
43
+ memory_management.load_models_gpu(
44
+ models=[self.patcher],
45
+ memory_required=inference_memory
46
+ )
47
+
48
+ def move_tensor_to_current_device(self, x):
49
+ return x.to(device=self.patcher.current_device, dtype=self.dtype)
modules_forge/forge_alter_samplers.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ from typing import Callable
3
+
4
+ import k_diffusion.sampling
5
+
6
+ from modules import sd_samplers_common, sd_samplers_kdiffusion
7
+
8
+
9
+ class AlterSampler(sd_samplers_kdiffusion.KDiffusionSampler):
10
+ def __init__(self, sd_model, sampler_name):
11
+ sampler_function: Callable = getattr(k_diffusion.sampling, f"sample_{sampler_name}", None)
12
+ if sampler_function is None:
13
+ raise ValueError(f"Unknown sampler: {sampler_name}")
14
+
15
+ super().__init__(sampler_function, sd_model, None)
16
+
17
+ def sample(self, p, *args, **kwargs):
18
+ if p.cfg_scale > 2.0:
19
+ logging.warning("CFG between 1.0 ~ 2.0 is recommended when using CFG++ samplers")
20
+ return super().sample(p, *args, **kwargs)
21
+
22
+ def sample_img2img(self, p, *args, **kwargs):
23
+ if p.cfg_scale > 2.0:
24
+ logging.warning("CFG between 1.0 ~ 2.0 is recommended when using CFG++ samplers")
25
+ return super().sample_img2img(p, *args, **kwargs)
26
+
27
+
28
+ def build_constructor(sampler_key: str) -> Callable:
29
+ def constructor(model):
30
+ return AlterSampler(model, sampler_key)
31
+
32
+ return constructor
33
+
34
+
35
+ def create_cfg_pp_sampler(sampler_name: str, sampler_key: str) -> "sd_samplers_common.SamplerData":
36
+ config = {}
37
+ base_name = sampler_name.removesuffix(" CFG++")
38
+ for name, _, _, params in sd_samplers_kdiffusion.samplers_k_diffusion:
39
+ if name == base_name:
40
+ config = params.copy()
41
+ break
42
+
43
+ return sd_samplers_common.SamplerData(sampler_name, build_constructor(sampler_key=sampler_key), [sampler_key], config)
44
+
45
+
46
+ samplers_data_alter = [
47
+ create_cfg_pp_sampler("DPM++ 2M CFG++", "dpmpp_2m_cfg_pp"),
48
+ create_cfg_pp_sampler("Euler a CFG++", "euler_ancestral_cfg_pp"),
49
+ create_cfg_pp_sampler("Euler CFG++", "euler_cfg_pp"),
50
+ ]
modules_forge/forge_canvas/canvas.css ADDED
@@ -0,0 +1,160 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .forge-container {
2
+ width: 100%;
3
+ height: 512px;
4
+ position: relative;
5
+ overflow: hidden;
6
+ user-select: none;
7
+ }
8
+
9
+ .forge-image-container:not(.plain) {
10
+ background-color: #cccccc;
11
+ background-image:
12
+ linear-gradient(45deg, #eee 25%, transparent 25%, transparent 75%, #eee 75%, #eee),
13
+ linear-gradient(45deg, #eee 25%, transparent 25%, transparent 75%, #eee 75%, #eee);
14
+ background-size: 20px 20px;
15
+ background-position:
16
+ 0 0,
17
+ 10px 10px;
18
+ }
19
+
20
+ .forge-image-container {
21
+ width: 100%;
22
+ height: calc(100% - 6px);
23
+ position: relative;
24
+ overflow: hidden;
25
+ }
26
+
27
+ .forge-image {
28
+ position: absolute;
29
+ top: 0;
30
+ left: 0;
31
+ background-size: contain;
32
+ background-repeat: no-repeat;
33
+ cursor: grab;
34
+ max-width: unset !important;
35
+ max-height: unset !important;
36
+ }
37
+
38
+ .forge-image:active {
39
+ cursor: grabbing;
40
+ }
41
+
42
+ .forge-file-upload {
43
+ display: none;
44
+ }
45
+
46
+ .forge-toolbar-static {
47
+ position: absolute;
48
+ top: 0px;
49
+ left: 0px;
50
+ z-index: 10 !important;
51
+ background: rgba(47, 47, 47, 0.8);
52
+ padding: 6px 10px;
53
+ opacity: 1 !important;
54
+ }
55
+
56
+ .forge-toolbar {
57
+ position: absolute;
58
+ top: 0px;
59
+ left: 0px;
60
+ z-index: 10;
61
+ background: rgba(47, 47, 47, 0.8);
62
+ padding: 6px 10px;
63
+ opacity: 0;
64
+ transition: opacity 0.3s ease;
65
+ }
66
+
67
+ .forge-toolbar .forge-btn,
68
+ .forge-toolbar-static .forge-btn {
69
+ padding: 2px 6px;
70
+ border: none;
71
+ background-color: #4a4a4a;
72
+ color: white;
73
+ font-size: 14px;
74
+ cursor: pointer;
75
+ transition: background-color 0.3s ease;
76
+ }
77
+
78
+ .forge-toolbar .forge-btn,
79
+ .forge-toolbar-static .forge-btn:hover {
80
+ background-color: #5e5e5e;
81
+ }
82
+
83
+ .forge-toolbar .forge-btn,
84
+ .forge-toolbar-static .forge-btn:active {
85
+ background-color: #3e3e3e;
86
+ }
87
+
88
+ .forge-toolbar-box-a {
89
+ flex-wrap: wrap;
90
+ }
91
+
92
+ .forge-toolbar-box-b {
93
+ display: flex;
94
+ flex-wrap: wrap;
95
+ align-items: center;
96
+ justify-content: center;
97
+ gap: 4px;
98
+ }
99
+
100
+ .forge-color-picker-block {
101
+ display: flex;
102
+ align-items: center;
103
+ }
104
+
105
+ .forge-range-row {
106
+ display: flex;
107
+ flex-direction: column;
108
+ align-items: center;
109
+ justify-content: center;
110
+ }
111
+
112
+ .forge-toolbar-color {
113
+ border: none;
114
+ background: none;
115
+ padding: 3px;
116
+ border-radius: 50%;
117
+ width: 20px;
118
+ height: 20px;
119
+ -webkit-appearance: none;
120
+ appearance: none;
121
+ cursor: pointer;
122
+ }
123
+
124
+ .forge-toolbar-color::-webkit-color-swatch-wrapper {
125
+ padding: 0;
126
+ border-radius: 50%;
127
+ }
128
+
129
+ .forge-toolbar-color::-webkit-color-swatch {
130
+ border: none;
131
+ border-radius: 50%;
132
+ background: none;
133
+ }
134
+
135
+ .forge-toolbar-label {
136
+ color: white !important;
137
+ padding: 0 4px;
138
+ display: flex;
139
+ align-items: center;
140
+ margin-bottom: 4px;
141
+ }
142
+
143
+ .forge-scribble-indicator {
144
+ position: relative;
145
+ border-radius: 50%;
146
+ border: 1px solid;
147
+ pointer-events: none;
148
+ display: none;
149
+ width: 80px;
150
+ height: 80px;
151
+ }
152
+
153
+ .forge-upload-hint {
154
+ position: absolute;
155
+ top: 50%;
156
+ left: 50%;
157
+ width: 30%;
158
+ height: 30%;
159
+ transform: translate(-50%, -50%);
160
+ }
modules_forge/forge_canvas/canvas.html ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <div class="forge-container" id="container_forge_mixin">
2
+ <input type="file" id="imageInput_forge_mixin" class="forge-file-upload">
3
+ <div id="imageContainer_forge_mixin" class="forge-image-container">
4
+ <div id="uploadHint_forge_mixin">
5
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="4"
6
+ stroke-linecap="round" stroke-linejoin="round" class="forge-upload-hint">
7
+ <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path>
8
+ <polyline points="17 8 12 3 7 8"></polyline>
9
+ <line x1="12" y1="3" x2="12" y2="15"></line>
10
+ </svg>
11
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="grey" stroke-width="2"
12
+ stroke-linecap="round" stroke-linejoin="round" class="forge-upload-hint">
13
+ <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path>
14
+ <polyline points="17 8 12 3 7 8"></polyline>
15
+ <line x1="12" y1="3" x2="12" y2="15"></line>
16
+ </svg>
17
+ </div>
18
+ <img id="image_forge_mixin" draggable="false" class="forge-image">
19
+ <canvas id="drawingCanvas_forge_mixin" class="forge-drawing-canvas" style="position:absolute;top:0;left:0;"
20
+ width="1" height="1"></canvas>
21
+ <div class="forge-toolbar" id="toolbar_forge_mixin" title="[Shift] for Eraser">
22
+ <div class="forge-toolbar-box-a">
23
+ <button id="maxButton_forge_mixin" class="forge-btn" title="Maximize [F]">⛶</button>
24
+ <button id="minButton_forge_mixin" class="forge-btn" title="Minimize [F]">➖</button>
25
+ <button id="uploadButton_forge_mixin" class="forge-btn" title="Upload">📂</button>
26
+ <button id="removeButton_forge_mixin" class="forge-btn" title="Remove">🗑️</button>
27
+ <button id="centerButton_forge_mixin" class="forge-btn" title="Center Position [R]">✠</button>
28
+ <button id="resetButton_forge_mixin" class="forge-btn" title="Reset [Ctrl + X]">🔄</button>
29
+ <button id="undoButton_forge_mixin" class="forge-btn" title="Undo [Ctrl + Z]">↩️</button>
30
+ <button id="redoButton_forge_mixin" class="forge-btn" title="Redo [Ctrl + Y]">↪️</button>
31
+ </div>
32
+ <div class="forge-toolbar-box-b">
33
+ <div class="forge-color-picker-block" title="Color Picker [E]" id="scribbleColorBlock_forge_mixin">
34
+ <input type="color" id="scribbleColor_forge_mixin" class="forge-toolbar-color" value="#000000">
35
+ </div>
36
+ <div class="forge-range-row" title="adjust with [W] + [Scroll Wheel]"
37
+ id="scribbleWidthBlock_forge_mixin">
38
+ <div id="widthLabel_forge_mixin" class="forge-toolbar-label">Brush Width</div>
39
+ <input type="range" id="scribbleWidth_forge_mixin" class="forge-toolbar-range" min="1" max="100"
40
+ value="25">
41
+ </div>
42
+ <div class="forge-range-row" title="adjust with [A] + [Scroll Wheel]&#10;function as eraser if 0"
43
+ id="scribbleAlphaBlock_forge_mixin">
44
+ <div id="alphaLabel_forge_mixin" class="forge-toolbar-label">Brush Opacity</div>
45
+ <input type="range" id="scribbleAlpha_forge_mixin" class="forge-toolbar-range" min="0" max="100"
46
+ value="100">
47
+ </div>
48
+ <div class="forge-range-row" title="adjust with [S] + [Scroll Wheel]"
49
+ id="scribbleSoftnessBlock_forge_mixin">
50
+ <div id="softnessLabel_forge_mixin" class="forge-toolbar-label">Brush Softness</div>
51
+ <input type="range" id="scribbleSoftness_forge_mixin" class="forge-toolbar-range" min="0" max="100"
52
+ value="0">
53
+ </div>
54
+ </div>
55
+ </div>
56
+ <div id="scribbleIndicator_forge_mixin" class="forge-scribble-indicator"></div>
57
+ </div>
58
+ </div>
modules_forge/forge_canvas/canvas.js ADDED
@@ -0,0 +1,840 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ class GradioTextAreaBind {
2
+ constructor(id, className) {
3
+ this.target = document.querySelector(`#${id}.${className} textarea`);
4
+ this.sync_lock = false;
5
+ this.previousValue = "";
6
+ }
7
+
8
+ set_value(value) {
9
+ if (this.sync_lock) return;
10
+ this.sync_lock = true;
11
+ this.target.value = value;
12
+ this.previousValue = value;
13
+ const event = new Event("input", { bubbles: true });
14
+ Object.defineProperty(event, "target", { value: this.target });
15
+ this.target.dispatchEvent(event);
16
+ this.previousValue = value;
17
+ this.sync_lock = false;
18
+ }
19
+
20
+ listen(callback) {
21
+ setInterval(() => {
22
+ if (this.target.value !== this.previousValue) {
23
+ this.previousValue = this.target.value;
24
+ if (this.sync_lock) return;
25
+ this.sync_lock = true;
26
+ callback(this.target.value);
27
+ this.sync_lock = false;
28
+ }
29
+ }, 100);
30
+ }
31
+ }
32
+
33
+ class ForgeCanvas {
34
+ constructor(
35
+ uuid,
36
+ no_upload = false,
37
+ no_scribbles = false,
38
+ contrast_scribbles = false,
39
+ initial_height = 512,
40
+ scribbleColor = "#000000",
41
+ scribbleColorFixed = false,
42
+ scribbleWidth = 20,
43
+ scribbleWidthFixed = false,
44
+ scribbleWidthConsistent = false,
45
+ scribbleAlpha = 100,
46
+ scribbleAlphaFixed = false,
47
+ scribbleSoftness = 0,
48
+ scribbleSoftnessFixed = false,
49
+ ) {
50
+ this.gradio_config = gradio_config;
51
+ this.uuid = uuid;
52
+
53
+ this.no_upload = no_upload;
54
+ this.no_scribbles = no_scribbles;
55
+ this.contrast_scribbles = contrast_scribbles;
56
+
57
+ this.img = null;
58
+ this.imgX = 0;
59
+ this.imgY = 0;
60
+ this.orgWidth = 0;
61
+ this.orgHeight = 0;
62
+ this.imgScale = 1.0;
63
+ this.initial_height = initial_height;
64
+
65
+ this.dragging = false;
66
+ this.dragged_just_now = false;
67
+ this.drawing = false;
68
+ this.contrast_pattern = null;
69
+
70
+ this.scribbleColor = scribbleColor;
71
+ this.scribbleColorFixed = scribbleColorFixed;
72
+ this.scribbleWidth = scribbleWidth;
73
+ this.scribbleWidthFixed = scribbleWidthFixed;
74
+ this.scribbleWidthConsistent = scribbleWidthConsistent;
75
+ this.scribbleAlpha = scribbleAlpha;
76
+ this.scribbleAlphaFixed = scribbleAlphaFixed;
77
+ this.scribbleSoftness = scribbleSoftness;
78
+ this.scribbleSoftnessFixed = scribbleSoftnessFixed;
79
+
80
+ this.history = [];
81
+ this.historyIndex = -1;
82
+ this.maximized = false;
83
+ this.originalState = {};
84
+ this.pointerInsideContainer = false;
85
+ this.temp_canvas = document.createElement("canvas");
86
+ this.temp_draw_points = [];
87
+ this.temp_draw_bg = null;
88
+
89
+ this.background_gradio_bind = new GradioTextAreaBind(this.uuid, "logical_image_background");
90
+ this.foreground_gradio_bind = new GradioTextAreaBind(this.uuid, "logical_image_foreground");
91
+ this.init();
92
+
93
+ this._held_W = false;
94
+ this._held_A = false;
95
+ this._held_S = false;
96
+
97
+ this._original_alpha = null;
98
+ }
99
+
100
+ init() {
101
+ const self = this;
102
+
103
+ const container = document.getElementById(`container_${self.uuid}`);
104
+ const imageContainer = document.getElementById(`imageContainer_${self.uuid}`);
105
+ const drawingCanvas = document.getElementById(`drawingCanvas_${self.uuid}`);
106
+ const toolbar = document.getElementById(`toolbar_${self.uuid}`);
107
+
108
+ const maxButton = document.getElementById(`maxButton_${self.uuid}`);
109
+ const minButton = document.getElementById(`minButton_${self.uuid}`);
110
+ const uploadButton = document.getElementById(`uploadButton_${self.uuid}`);
111
+ const removeButton = document.getElementById(`removeButton_${self.uuid}`);
112
+ const centerButton = document.getElementById(`centerButton_${self.uuid}`);
113
+ const resetButton = document.getElementById(`resetButton_${self.uuid}`);
114
+ const undoButton = document.getElementById(`undoButton_${self.uuid}`);
115
+ const redoButton = document.getElementById(`redoButton_${self.uuid}`);
116
+
117
+ const uploadHint = document.getElementById(`uploadHint_${self.uuid}`);
118
+ const scribbleIndicator = document.getElementById(`scribbleIndicator_${self.uuid}`);
119
+
120
+ minButton.style.display = "none";
121
+ this.maximized = false;
122
+
123
+ const scribbleColorBlock = document.getElementById(`scribbleColorBlock_${self.uuid}`);
124
+ if (self.scribbleColorFixed) scribbleColorBlock.style.display = "none";
125
+ const scribbleColor = document.getElementById(`scribbleColor_${self.uuid}`);
126
+ scribbleColor.value = self.scribbleColor;
127
+
128
+ const scribbleWidthBlock = document.getElementById(`scribbleWidthBlock_${self.uuid}`);
129
+ if (self.scribbleWidthFixed) scribbleWidthBlock.style.display = "none";
130
+ const scribbleWidth = document.getElementById(`scribbleWidth_${self.uuid}`);
131
+ const scribbleWidthLabel = document.getElementById(`widthLabel_${self.uuid}`);
132
+ scribbleWidth.value = self.scribbleWidth;
133
+ scribbleWidthLabel.textContent = `Brush Width (${self.scribbleWidth})`;
134
+
135
+ const scribbleAlphaBlock = document.getElementById(`scribbleAlphaBlock_${self.uuid}`);
136
+ if (self.scribbleAlphaFixed) scribbleAlphaBlock.style.display = "none";
137
+ const scribbleAlpha = document.getElementById(`scribbleAlpha_${self.uuid}`);
138
+ const scribbleAlphaLabel = document.getElementById(`alphaLabel_${self.uuid}`);
139
+ scribbleAlpha.value = self.scribbleAlpha;
140
+ scribbleAlphaLabel.textContent = `Brush Opacity (${self.scribbleAlpha})`;
141
+
142
+ const scribbleSoftnessBlock = document.getElementById(`scribbleSoftnessBlock_${self.uuid}`);
143
+ if (self.scribbleSoftnessFixed) scribbleSoftnessBlock.style.display = "none";
144
+ const scribbleSoftness = document.getElementById(`scribbleSoftness_${self.uuid}`);
145
+ const scribbleSoftnessLabel = document.getElementById(`softnessLabel_${self.uuid}`);
146
+ scribbleSoftness.value = self.scribbleSoftness;
147
+ scribbleSoftnessLabel.textContent = `Brush Softness (${self.scribbleSoftness})`;
148
+
149
+ const indicatorSize = self.scribbleWidth * 4;
150
+ scribbleIndicator.style.width = `${indicatorSize}px`;
151
+ scribbleIndicator.style.height = `${indicatorSize}px`;
152
+
153
+ container.style.height = `${self.initial_height}px`;
154
+ drawingCanvas.width = imageContainer.clientWidth;
155
+ drawingCanvas.height = imageContainer.clientHeight;
156
+
157
+ const drawContext = drawingCanvas.getContext("2d");
158
+ self.drawingCanvas_ = drawingCanvas;
159
+
160
+ if (self.no_scribbles) {
161
+ toolbar.querySelector(".forge-toolbar-box-b").style.display = "none";
162
+ toolbar.removeAttribute("title");
163
+ resetButton.style.display = "none";
164
+ undoButton.style.display = "none";
165
+ redoButton.style.display = "none";
166
+ }
167
+
168
+ if (self.no_upload) {
169
+ uploadButton.style.display = "none";
170
+ uploadHint.style.display = "none";
171
+ }
172
+
173
+ if (self.contrast_scribbles) {
174
+ const size = 10;
175
+ const tempCanvas = self.temp_canvas;
176
+ tempCanvas.width = size * 2;
177
+ tempCanvas.height = size * 2;
178
+ const tempCtx = tempCanvas.getContext("2d");
179
+ tempCtx.fillStyle = "#ffffff";
180
+ tempCtx.fillRect(0, 0, size, size);
181
+ tempCtx.fillRect(size, size, size, size);
182
+ tempCtx.fillStyle = "#000000";
183
+ tempCtx.fillRect(size, 0, size, size);
184
+ tempCtx.fillRect(0, size, size, size);
185
+ self.contrast_pattern = drawContext.createPattern(tempCanvas, "repeat");
186
+ drawingCanvas.style.opacity = "0.5";
187
+ }
188
+
189
+ function resetScribble(e, rect) {
190
+ const indicatorSize = self.scribbleWidth * (self.scribbleWidthConsistent ? 1.0 : self.imgScale) * 4;
191
+ scribbleIndicator.style.width = `${indicatorSize}px`;
192
+ scribbleIndicator.style.height = `${indicatorSize}px`;
193
+ scribbleIndicator.style.left = `${e.clientX - rect.left - indicatorSize / 2}px`;
194
+ scribbleIndicator.style.top = `${e.clientY - rect.top - indicatorSize / 2}px`;
195
+ }
196
+
197
+ const resizeObserver = new ResizeObserver(() => {
198
+ self.adjustInitialPositionAndScale();
199
+ self.drawImage();
200
+ });
201
+ resizeObserver.observe(container);
202
+
203
+ document.getElementById(`imageInput_${self.uuid}`).addEventListener("change", (e) => {
204
+ self.handleFileUpload(e.target.files[0]);
205
+ });
206
+
207
+ uploadButton.addEventListener("click", () => {
208
+ if (self.no_upload) return;
209
+ document.getElementById(`imageInput_${self.uuid}`).click();
210
+ });
211
+
212
+ removeButton.addEventListener("click", () => {
213
+ self.resetImage();
214
+ self.removeImage();
215
+ });
216
+
217
+ centerButton.addEventListener("click", () => {
218
+ self.adjustInitialPositionAndScale();
219
+ self.drawImage();
220
+ });
221
+
222
+ resetButton.addEventListener("click", () => {
223
+ self.resetImage();
224
+ });
225
+
226
+ undoButton.addEventListener("click", () => {
227
+ self.undo();
228
+ });
229
+
230
+ redoButton.addEventListener("click", () => {
231
+ self.redo();
232
+ });
233
+
234
+ scribbleColor.addEventListener("input", (e) => {
235
+ self.scribbleColor = e.target.value;
236
+ scribbleIndicator.style.borderColor = self.scribbleColor;
237
+ });
238
+
239
+ scribbleWidth.addEventListener("input", (e) => {
240
+ self.scribbleWidth = e.target.value;
241
+ scribbleWidthLabel.textContent = `Brush Width (${self.scribbleWidth})`;
242
+ const indicatorSize = self.scribbleWidth * (self.scribbleWidthConsistent ? 1.0 : self.imgScale) * 4;
243
+ scribbleIndicator.style.width = `${indicatorSize}px`;
244
+ scribbleIndicator.style.height = `${indicatorSize}px`;
245
+ });
246
+
247
+ scribbleAlpha.addEventListener("input", (e) => {
248
+ self.scribbleAlpha = e.target.value;
249
+ scribbleAlphaLabel.textContent = `Brush Opacity (${self.scribbleAlpha})`;
250
+ });
251
+
252
+ scribbleSoftness.addEventListener("input", (e) => {
253
+ self.scribbleSoftness = e.target.value;
254
+ scribbleSoftnessLabel.textContent = `Brush Softness (${self.scribbleSoftness})`;
255
+ });
256
+
257
+ drawingCanvas.addEventListener("pointerdown", (e) => {
258
+ if (!self.img || e.button !== 0 || self.no_scribbles) return;
259
+ const rect = drawingCanvas.getBoundingClientRect();
260
+ self.drawing = true;
261
+ drawingCanvas.style.cursor = "crosshair";
262
+ scribbleIndicator.style.display = "none";
263
+ self.temp_draw_points = [[(e.clientX - rect.left) / self.imgScale, (e.clientY - rect.top) / self.imgScale]];
264
+ self.temp_draw_bg = drawContext.getImageData(0, 0, drawingCanvas.width, drawingCanvas.height);
265
+ self.handleDraw(e);
266
+ });
267
+
268
+ drawingCanvas.addEventListener("pointermove", (e) => {
269
+ if (self.drawing) self.handleDraw(e);
270
+ if (self.img && !self.drawing && !self.dragging && !self.no_scribbles) {
271
+ const rect = container.getBoundingClientRect();
272
+ resetScribble(e, rect);
273
+ scribbleIndicator.style.display = "inline-block";
274
+ }
275
+ });
276
+
277
+ toolbar.addEventListener("pointerdown", (e) => {
278
+ e.stopPropagation();
279
+ });
280
+
281
+ drawingCanvas.addEventListener("pointerup", () => {
282
+ self.drawing = false;
283
+ drawingCanvas.style.cursor = "";
284
+ self.saveState();
285
+ });
286
+
287
+ drawingCanvas.addEventListener("pointerout", () => {
288
+ self.drawing = false;
289
+ drawingCanvas.style.cursor = "";
290
+ scribbleIndicator.style.display = "none";
291
+ });
292
+
293
+ container.addEventListener("pointerdown", (e) => {
294
+ const rect = container.getBoundingClientRect();
295
+ const x = e.clientX - rect.left;
296
+ const y = e.clientY - rect.top;
297
+ if (e.button === 2 && self.isInsideImage(x, y)) {
298
+ self.dragging = true;
299
+ self.offsetX = x - self.imgX;
300
+ self.offsetY = y - self.imgY;
301
+ imageContainer.style.cursor = "grabbing";
302
+ drawingCanvas.style.cursor = "grabbing";
303
+ scribbleIndicator.style.display = "none";
304
+ } else if (e.button === 0 && !self.img && !self.no_upload) {
305
+ document.getElementById(`imageInput_${self.uuid}`).click();
306
+ }
307
+ });
308
+
309
+ container.addEventListener("pointermove", (e) => {
310
+ if (self.dragging) {
311
+ const rect = container.getBoundingClientRect();
312
+ const x = e.clientX - rect.left;
313
+ const y = e.clientY - rect.top;
314
+ self.imgX = x - self.offsetX;
315
+ self.imgY = y - self.offsetY;
316
+ self.drawImage();
317
+ self.dragged_just_now = true;
318
+ }
319
+ });
320
+
321
+ container.addEventListener("pointerup", (e) => {
322
+ if (self.dragging) self.handleDragEnd(e, false);
323
+ });
324
+
325
+ container.addEventListener("pointerout", (e) => {
326
+ if (self.dragging) self.handleDragEnd(e, true);
327
+ });
328
+
329
+ container.addEventListener("wheel", (e) => {
330
+ if (!self.img) return;
331
+ e.preventDefault();
332
+ const delta = e.deltaY * -0.001;
333
+ let scale = true;
334
+
335
+ if (this._held_W) {
336
+ // Width
337
+ scribbleWidth.value = parseInt(scribbleWidth.value) - Math.sign(e.deltaY) * 3;
338
+ updateInput(scribbleWidth);
339
+ const rect = container.getBoundingClientRect();
340
+ resetScribble(e, rect);
341
+ scale = false;
342
+ }
343
+ if (this._held_A) {
344
+ // Alpha (Opacity)
345
+ scribbleAlpha.value = parseInt(scribbleAlpha.value) - Math.sign(e.deltaY) * 5;
346
+ updateInput(scribbleAlpha);
347
+ scale = false;
348
+ }
349
+ if (this._held_S) {
350
+ // Softness
351
+ scribbleSoftness.value = parseInt(scribbleSoftness.value) - Math.sign(e.deltaY) * 5;
352
+ updateInput(scribbleSoftness);
353
+ scale = false;
354
+ }
355
+
356
+ if (!scale) return;
357
+
358
+ const rect = container.getBoundingClientRect();
359
+ const x = e.clientX - rect.left;
360
+ const y = e.clientY - rect.top;
361
+ const oldScale = self.imgScale;
362
+ self.imgScale += delta;
363
+ self.imgScale = Math.max(0.1, self.imgScale);
364
+ const newScale = self.imgScale / oldScale;
365
+ self.imgX = x - (x - self.imgX) * newScale;
366
+ self.imgY = y - (y - self.imgY) * newScale;
367
+ self.drawImage();
368
+ resetScribble(e, rect);
369
+ });
370
+
371
+ container.addEventListener("contextmenu", (e) => {
372
+ e.preventDefault();
373
+ self.dragged_just_now = false;
374
+ return false;
375
+ });
376
+
377
+ container.addEventListener("dragleave", () => {
378
+ toolbar.style.opacity = "0";
379
+ imageContainer.style.cursor = "";
380
+ drawingCanvas.style.cursor = "";
381
+ container.style.cursor = "";
382
+ scribbleIndicator.style.display = "none";
383
+ });
384
+
385
+ function preventDefaults(e) {
386
+ e.preventDefault();
387
+ e.stopPropagation();
388
+ }
389
+
390
+ for (const e of ["dragenter", "dragover", "dragleave", "drop"]) {
391
+ container.addEventListener(e, preventDefaults, false);
392
+ }
393
+
394
+ container.addEventListener("dragenter", () => {
395
+ imageContainer.style.cursor = "copy";
396
+ drawingCanvas.style.cursor = "copy";
397
+ });
398
+
399
+ container.addEventListener("dragleave", () => {
400
+ imageContainer.style.cursor = "";
401
+ drawingCanvas.style.cursor = "";
402
+ });
403
+
404
+ container.addEventListener("drop", (e) => {
405
+ imageContainer.style.cursor = "";
406
+ drawingCanvas.style.cursor = "";
407
+ const dt = e.dataTransfer;
408
+ const files = dt.files;
409
+ if (files.length > 0) self.handleFileUpload(files[0]);
410
+ });
411
+
412
+ container.addEventListener("pointerenter", () => {
413
+ self.pointerInsideContainer = true;
414
+ toolbar.style.opacity = "1";
415
+ if (!self.img && !self.no_upload) container.style.cursor = "pointer";
416
+ });
417
+
418
+ container.addEventListener("pointerleave", () => {
419
+ self.pointerInsideContainer = false;
420
+ toolbar.style.opacity = "0";
421
+ });
422
+
423
+ document.addEventListener("paste", (e) => {
424
+ if (self.pointerInsideContainer) self.handlePaste(e);
425
+ });
426
+
427
+ document.addEventListener("keydown", (e) => {
428
+ if (!self.pointerInsideContainer) return;
429
+ if (e.shiftKey) {
430
+ e.preventDefault();
431
+ if (this._original_alpha === null)
432
+ this._original_alpha = scribbleAlpha.value;
433
+ scribbleAlpha.value = 0.0;
434
+ updateInput(scribbleAlpha);
435
+ scribbleIndicator.style.border = "2px dotted";
436
+ return;
437
+ }
438
+ if (e.ctrlKey && e.key === "z") {
439
+ e.preventDefault();
440
+ this.undo();
441
+ }
442
+ if (e.ctrlKey && e.key === "y") {
443
+ e.preventDefault();
444
+ this.redo();
445
+ }
446
+ if (e.ctrlKey && e.key === "x") {
447
+ e.preventDefault();
448
+ this.resetImage();
449
+ }
450
+ if (e.key === "e") {
451
+ scribbleColor.click();
452
+ }
453
+ if (e.key === "r") {
454
+ centerButton.click();
455
+ }
456
+ if (e.key === "f") {
457
+ if (maxButton.style.display === "none")
458
+ minButton.click();
459
+ else
460
+ maxButton.click();
461
+ }
462
+
463
+ if (e.key === "w") this._held_W = true;
464
+ if (e.key === "a") this._held_A = true;
465
+ if (e.key === "s") this._held_S = true;
466
+ });
467
+
468
+ document.addEventListener("keyup", () => {
469
+ this._held_W = false;
470
+ this._held_A = false;
471
+ this._held_S = false;
472
+
473
+ if (this._original_alpha !== null) {
474
+ scribbleAlpha.value = this._original_alpha;
475
+ this._original_alpha = null;
476
+ updateInput(scribbleAlpha);
477
+ scribbleIndicator.style.border = "1px solid";
478
+ }
479
+ });
480
+
481
+ maxButton.addEventListener("click", () => {
482
+ self.maximize();
483
+ });
484
+
485
+ minButton.addEventListener("click", () => {
486
+ self.minimize();
487
+ });
488
+
489
+ self.updateUndoRedoButtons();
490
+
491
+ self.background_gradio_bind.listen((value) => {
492
+ self.loadImage(value);
493
+ });
494
+
495
+ self.foreground_gradio_bind.listen((value) => {
496
+ self.loadDrawing(value);
497
+ });
498
+ }
499
+
500
+ handleDraw(e) {
501
+ const canvas = this.drawingCanvas_;
502
+ const ctx = canvas.getContext("2d");
503
+ const rect = canvas.getBoundingClientRect();
504
+ const x = (e.clientX - rect.left) / this.imgScale;
505
+ const y = (e.clientY - rect.top) / this.imgScale;
506
+
507
+ this.temp_draw_points.push([x, y]);
508
+ ctx.putImageData(this.temp_draw_bg, 0, 0);
509
+ ctx.beginPath();
510
+ ctx.moveTo(this.temp_draw_points[0][0], this.temp_draw_points[0][1]);
511
+
512
+ for (let i = 1; i < this.temp_draw_points.length; i++) {
513
+ ctx.lineTo(this.temp_draw_points[i][0], this.temp_draw_points[i][1]);
514
+ }
515
+
516
+ ctx.lineCap = "round";
517
+ ctx.lineJoin = "round";
518
+ ctx.lineWidth = this.scribbleWidth / (this.scribbleWidthConsistent ? this.imgScale : 1.0) * 4;
519
+
520
+ if (this.scribbleAlpha <= 0) {
521
+ ctx.globalCompositeOperation = "destination-out";
522
+ ctx.globalAlpha = 1.0;
523
+ ctx.stroke();
524
+ return;
525
+ }
526
+
527
+ ctx.globalCompositeOperation = "source-over";
528
+
529
+ if (this.contrast_scribbles) {
530
+ ctx.strokeStyle = this.contrast_pattern;
531
+ ctx.stroke();
532
+ return;
533
+ }
534
+
535
+ ctx.strokeStyle = this.scribbleColor;
536
+
537
+ canvas.style.opacity = 1.0;
538
+ let drawingAlpha = this.scribbleAlpha;
539
+
540
+ if (this.scribbleAlphaFixed) {
541
+ canvas.style.opacity = this.scribbleAlpha / 100.0;
542
+ drawingAlpha = 100.0;
543
+ }
544
+
545
+ if (this.scribbleSoftness <= 0) {
546
+ ctx.save();
547
+ ctx.globalCompositeOperation = "destination-out";
548
+ ctx.globalAlpha = 1.0;
549
+ ctx.stroke();
550
+ ctx.restore();
551
+
552
+ ctx.globalCompositeOperation = "source-over";
553
+ ctx.globalAlpha = drawingAlpha / 100.0;
554
+ ctx.stroke();
555
+ return;
556
+ }
557
+
558
+ const innerWidth = ctx.lineWidth * (1 - this.scribbleSoftness / 96);
559
+ const outerWidth = ctx.lineWidth * (1 + this.scribbleSoftness / 96);
560
+ const steps = Math.round(5 + this.scribbleSoftness / 5);
561
+ const stepWidth = (outerWidth - innerWidth) / (steps - 1);
562
+
563
+ ctx.globalAlpha = 1.0 - Math.pow(1.0 - Math.min(drawingAlpha / 100, 0.95), 1.0 / steps);
564
+
565
+ for (let i = 0; i < steps; i++) {
566
+ ctx.lineWidth = innerWidth + stepWidth * i;
567
+ ctx.stroke();
568
+ }
569
+ }
570
+
571
+ handleFileUpload(file) {
572
+ if (file && !this.no_upload) {
573
+ const reader = new FileReader();
574
+ reader.onload = (e) => {
575
+ this.loadImage(e.target.result);
576
+ };
577
+ reader.readAsDataURL(file);
578
+ }
579
+ }
580
+
581
+ handlePaste(e) {
582
+ const items = e.clipboardData.items;
583
+ for (let i = 0; i < items.length; i++) {
584
+ const item = items[i];
585
+ if (item.type.indexOf("image") !== -1) {
586
+ const file = item.getAsFile();
587
+ this.handleFileUpload(file);
588
+ break;
589
+ }
590
+ }
591
+ }
592
+
593
+ loadImage(base64) {
594
+ if (typeof this.gradio_config !== "undefined") {
595
+ if (!this.gradio_config.version.startsWith("4.")) return;
596
+ } else {
597
+ return;
598
+ }
599
+
600
+ const image = new Image();
601
+ image.onload = () => {
602
+ this.img = base64;
603
+ this.orgWidth = image.width;
604
+ this.orgHeight = image.height;
605
+ const canvas = document.getElementById(`drawingCanvas_${this.uuid}`);
606
+ if (canvas.width !== image.width || canvas.height !== image.height) {
607
+ canvas.width = image.width;
608
+ canvas.height = image.height;
609
+ }
610
+ this.adjustInitialPositionAndScale();
611
+ this.drawImage();
612
+ this.updateBackgroundImageData();
613
+ this.saveState();
614
+ this.updateUndoRedoButtons();
615
+ document.getElementById(`imageInput_${this.uuid}`).value = null;
616
+ document.getElementById(`uploadHint_${this.uuid}`).style.display = "none";
617
+ };
618
+
619
+ if (base64) {
620
+ image.src = base64;
621
+ } else {
622
+ this.img = null;
623
+ const canvas = document.getElementById(`drawingCanvas_${this.uuid}`);
624
+ canvas.width = 1;
625
+ canvas.height = 1;
626
+ this.adjustInitialPositionAndScale();
627
+ this.drawImage();
628
+ this.saveState();
629
+ this.updateUndoRedoButtons();
630
+ }
631
+ }
632
+
633
+ loadDrawing(base64) {
634
+ const image = new Image();
635
+ image.onload = () => {
636
+ const canvas = document.getElementById(`drawingCanvas_${this.uuid}`);
637
+ const ctx = canvas.getContext("2d");
638
+ ctx.clearRect(0, 0, canvas.width, canvas.height);
639
+ ctx.drawImage(image, 0, 0);
640
+ this.saveState();
641
+ };
642
+ if (base64) {
643
+ image.src = base64;
644
+ } else {
645
+ const canvas = document.getElementById(`drawingCanvas_${this.uuid}`);
646
+ const ctx = canvas.getContext("2d");
647
+ ctx.clearRect(0, 0, canvas.width, canvas.height);
648
+ this.saveState();
649
+ }
650
+ }
651
+
652
+ isInsideImage(x, y) {
653
+ const scaledWidth = this.orgWidth * this.imgScale;
654
+ const scaledHeight = this.orgHeight * this.imgScale;
655
+ return x > this.imgX && x < this.imgX + scaledWidth && y > this.imgY && y < this.imgY + scaledHeight;
656
+ }
657
+
658
+ drawImage() {
659
+ const image = document.getElementById(`image_${this.uuid}`);
660
+ const drawingCanvas = document.getElementById(`drawingCanvas_${this.uuid}`);
661
+ if (this.img) {
662
+ const scaledWidth = this.orgWidth * this.imgScale;
663
+ const scaledHeight = this.orgHeight * this.imgScale;
664
+ image.src = this.img;
665
+ image.style.width = `${scaledWidth}px`;
666
+ image.style.height = `${scaledHeight}px`;
667
+ image.style.left = `${this.imgX}px`;
668
+ image.style.top = `${this.imgY}px`;
669
+ image.style.display = "block";
670
+ drawingCanvas.style.width = `${scaledWidth}px`;
671
+ drawingCanvas.style.height = `${scaledHeight}px`;
672
+ drawingCanvas.style.left = `${this.imgX}px`;
673
+ drawingCanvas.style.top = `${this.imgY}px`;
674
+ } else {
675
+ image.src = "";
676
+ image.style.display = "none";
677
+ }
678
+ }
679
+
680
+ adjustInitialPositionAndScale() {
681
+ const container = document.getElementById(`container_${this.uuid}`);
682
+ const containerWidth = container.clientWidth - 20;
683
+ const containerHeight = container.clientHeight - 20;
684
+ const scaleX = containerWidth / this.orgWidth;
685
+ const scaleY = containerHeight / this.orgHeight;
686
+ this.imgScale = Math.min(scaleX, scaleY);
687
+ const scaledWidth = this.orgWidth * this.imgScale;
688
+ const scaledHeight = this.orgHeight * this.imgScale;
689
+ this.imgX = (container.clientWidth - scaledWidth) / 2;
690
+ this.imgY = (container.clientHeight - scaledHeight) / 2;
691
+ }
692
+
693
+ resetImage() {
694
+ const canvas = document.getElementById(`drawingCanvas_${this.uuid}`);
695
+ const ctx = canvas.getContext("2d");
696
+ ctx.clearRect(0, 0, canvas.width, canvas.height);
697
+ this.adjustInitialPositionAndScale();
698
+ this.drawImage();
699
+ this.saveState();
700
+ }
701
+
702
+ removeImage() {
703
+ this.img = null;
704
+ const image = document.getElementById(`image_${this.uuid}`);
705
+ const canvas = document.getElementById(`drawingCanvas_${this.uuid}`);
706
+ const ctx = canvas.getContext("2d");
707
+ ctx.clearRect(0, 0, canvas.width, canvas.height);
708
+ image.src = "";
709
+ image.style.width = "0";
710
+ image.style.height = "0";
711
+ this.saveState();
712
+ if (!this.no_upload) {
713
+ document.getElementById(`uploadHint_${this.uuid}`).style.display = "inline-block";
714
+ }
715
+ this.loadImage(null);
716
+ }
717
+
718
+ saveState() {
719
+ const canvas = document.getElementById(`drawingCanvas_${this.uuid}`);
720
+ const ctx = canvas.getContext("2d");
721
+ const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
722
+ this.history = this.history.slice(0, this.historyIndex + 1);
723
+ this.history.push(imageData);
724
+ this.historyIndex++;
725
+ this.updateUndoRedoButtons();
726
+ this.updateDrawingData();
727
+ }
728
+
729
+ undo() {
730
+ if (this.historyIndex > 0) {
731
+ this.historyIndex--;
732
+ this.restoreState();
733
+ this.updateUndoRedoButtons();
734
+ }
735
+ }
736
+
737
+ redo() {
738
+ if (this.historyIndex < this.history.length - 1) {
739
+ this.historyIndex++;
740
+ this.restoreState();
741
+ this.updateUndoRedoButtons();
742
+ }
743
+ }
744
+
745
+ restoreState() {
746
+ const canvas = document.getElementById(`drawingCanvas_${this.uuid}`);
747
+ const ctx = canvas.getContext("2d");
748
+ const imageData = this.history[this.historyIndex];
749
+ ctx.putImageData(imageData, 0, 0);
750
+ this.updateDrawingData();
751
+ }
752
+
753
+ updateUndoRedoButtons() {
754
+ const undoButton = document.getElementById(`undoButton_${this.uuid}`);
755
+ const redoButton = document.getElementById(`redoButton_${this.uuid}`);
756
+ undoButton.disabled = this.historyIndex <= 0;
757
+ redoButton.disabled = this.historyIndex >= this.history.length - 1;
758
+ undoButton.style.opacity = undoButton.disabled ? "0.5" : "1";
759
+ redoButton.style.opacity = redoButton.disabled ? "0.5" : "1";
760
+ }
761
+
762
+ updateBackgroundImageData() {
763
+ if (!this.img) {
764
+ this.background_gradio_bind.set_value("");
765
+ return;
766
+ }
767
+ const image = document.getElementById(`image_${this.uuid}`);
768
+ const tempCanvas = this.temp_canvas;
769
+ const tempCtx = tempCanvas.getContext("2d");
770
+ tempCanvas.width = this.orgWidth;
771
+ tempCanvas.height = this.orgHeight;
772
+ tempCtx.drawImage(image, 0, 0, this.orgWidth, this.orgHeight);
773
+ const dataUrl = tempCanvas.toDataURL("image/png");
774
+ this.background_gradio_bind.set_value(dataUrl);
775
+ }
776
+
777
+ updateDrawingData() {
778
+ if (!this.img) {
779
+ this.foreground_gradio_bind.set_value("");
780
+ return;
781
+ }
782
+ const canvas = document.getElementById(`drawingCanvas_${this.uuid}`);
783
+ const dataUrl = canvas.toDataURL("image/png");
784
+ this.foreground_gradio_bind.set_value(dataUrl);
785
+ }
786
+
787
+ maximize() {
788
+ if (this.maximized) return;
789
+ const container = document.getElementById(`container_${this.uuid}`);
790
+ const maxButton = document.getElementById(`maxButton_${this.uuid}`);
791
+ const minButton = document.getElementById(`minButton_${this.uuid}`);
792
+
793
+ this.originalState = {
794
+ width: container.style.width,
795
+ height: container.style.height,
796
+ top: container.style.top,
797
+ left: container.style.left,
798
+ position: container.style.position,
799
+ zIndex: container.style.zIndex,
800
+ };
801
+
802
+ container.style.width = "100vw";
803
+ container.style.height = "100vh";
804
+ container.style.top = "0";
805
+ container.style.left = "0";
806
+ container.style.position = "fixed";
807
+ container.style.zIndex = "1000";
808
+ maxButton.style.display = "none";
809
+ minButton.style.display = "inline-block";
810
+ this.maximized = true;
811
+ }
812
+
813
+ minimize() {
814
+ if (!this.maximized) return;
815
+ const container = document.getElementById(`container_${this.uuid}`);
816
+ const maxButton = document.getElementById(`maxButton_${this.uuid}`);
817
+ const minButton = document.getElementById(`minButton_${this.uuid}`);
818
+
819
+ container.style.width = this.originalState.width;
820
+ container.style.height = this.originalState.height;
821
+ container.style.top = this.originalState.top;
822
+ container.style.left = this.originalState.left;
823
+ container.style.position = this.originalState.position;
824
+ container.style.zIndex = this.originalState.zIndex;
825
+ maxButton.style.display = "inline-block";
826
+ minButton.style.display = "none";
827
+ this.maximized = false;
828
+ }
829
+
830
+ handleDragEnd(e, isPointerOut) {
831
+ const image = document.getElementById(`image_${this.uuid}`);
832
+ const drawingCanvas = document.getElementById(`drawingCanvas_${this.uuid}`);
833
+ this.dragging = false;
834
+ image.style.cursor = "grab";
835
+ drawingCanvas.style.cursor = "grab";
836
+ }
837
+ }
838
+
839
+ const True = true;
840
+ const False = false;
modules_forge/forge_canvas/canvas.py ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Forge Canvas
3
+ Copyright (C) 2024 lllyasviel
4
+
5
+ This program is free software: you can redistribute it and/or modify
6
+ it under the terms of the GNU Affero General Public License as published by
7
+ the Free Software Foundation, either version 3 of the License, or
8
+ (at your option) any later version.
9
+
10
+ This program is distributed in the hope that it will be useful,
11
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
+ GNU Affero General Public License for more details.
14
+ """
15
+
16
+ import gradio.component_meta
17
+
18
+ create_or_modify_pyi_org = gradio.component_meta.create_or_modify_pyi
19
+
20
+
21
+ def create_or_modify_pyi_org_patched(component_class, class_name, events):
22
+ try:
23
+ if component_class.__name__ == "LogicalImage":
24
+ return
25
+ return create_or_modify_pyi_org(component_class, class_name, events)
26
+ except Exception:
27
+ return
28
+
29
+
30
+ gradio.component_meta.create_or_modify_pyi = create_or_modify_pyi_org_patched
31
+
32
+
33
+ import base64
34
+ import os
35
+ import uuid
36
+ from functools import wraps
37
+ from io import BytesIO
38
+
39
+ import gradio as gr
40
+ import numpy as np
41
+ from gradio.context import Context
42
+ from PIL import Image
43
+
44
+ from modules.shared import opts
45
+
46
+ DEBUG_MODE = False
47
+ canvas_js_root_path = os.path.dirname(__file__)
48
+
49
+
50
+ def web_js(file_name):
51
+ full_path = os.path.join(canvas_js_root_path, file_name)
52
+ return f'<script src="file={full_path}?{os.path.getmtime(full_path)}"></script>\n'
53
+
54
+
55
+ def web_css(file_name):
56
+ full_path = os.path.join(canvas_js_root_path, file_name)
57
+ return f'<link rel="stylesheet" href="file={full_path}?{os.path.getmtime(full_path)}">\n'
58
+
59
+
60
+ canvas_html = open(os.path.join(canvas_js_root_path, "canvas.html"), encoding="utf-8").read()
61
+ canvas_head = "".join((web_css("canvas.css"), web_js("canvas.js")))
62
+
63
+
64
+ def image_to_base64(image_array, numpy=True):
65
+ image = Image.fromarray(image_array) if numpy else image_array
66
+ image = image.convert("RGBA")
67
+ buffered = BytesIO()
68
+ image.save(buffered, format="PNG")
69
+ image_base64 = base64.b64encode(buffered.getvalue()).decode("utf-8")
70
+ return f"data:image/png;base64,{image_base64}"
71
+
72
+
73
+ def base64_to_image(base64_str, numpy=True):
74
+ if base64_str.startswith("data:image/png;base64,"):
75
+ base64_str = base64_str.replace("data:image/png;base64,", "")
76
+ image_data = base64.b64decode(base64_str)
77
+ image = Image.open(BytesIO(image_data))
78
+ image = image.convert("RGBA")
79
+ image_array = np.array(image) if numpy else image
80
+ return image_array
81
+
82
+
83
+ class LogicalImage(gr.Textbox):
84
+ @wraps(gr.Textbox.__init__)
85
+ def __init__(self, *args, numpy=True, **kwargs):
86
+ self.numpy = numpy
87
+ self.infotext = dict()
88
+
89
+ if "value" in kwargs:
90
+ initial_value = kwargs["value"]
91
+ if initial_value is not None:
92
+ kwargs["value"] = self.image_to_base64(initial_value)
93
+ else:
94
+ del kwargs["value"]
95
+
96
+ super().__init__(*args, **kwargs)
97
+
98
+ def preprocess(self, payload):
99
+ if not isinstance(payload, str):
100
+ return None
101
+
102
+ if not payload.startswith("data:image/png;base64,"):
103
+ return None
104
+
105
+ image = base64_to_image(payload, numpy=self.numpy)
106
+ if hasattr(image, "info"):
107
+ image.info = self.infotext
108
+
109
+ return image
110
+
111
+ def postprocess(self, value):
112
+ if value is None:
113
+ return None
114
+
115
+ if hasattr(value, "info"):
116
+ self.infotext = value.info
117
+
118
+ return image_to_base64(value, numpy=self.numpy)
119
+
120
+ def get_block_name(self):
121
+ return "textbox"
122
+
123
+
124
+ class ForgeCanvas:
125
+ def __init__(self, no_upload=False, no_scribbles=False, contrast_scribbles=False, height=None, scribble_color="#000000", scribble_color_fixed=False, scribble_width=25, scribble_width_fixed=False, scribble_alpha=100, scribble_alpha_fixed=False, scribble_softness=0, scribble_softness_fixed=False, visible=True, numpy=False, initial_image=None, elem_id=None, elem_classes=None):
126
+ self.uuid = "uuid_" + uuid.uuid4().hex
127
+
128
+ canvas_html_uuid = canvas_html.replace("forge_mixin", self.uuid)
129
+
130
+ if opts.forge_canvas_plain:
131
+ canvas_html_uuid = canvas_html_uuid.replace('class="forge-image-container"', f'class="forge-image-container plain" style="background-color: {opts.forge_canvas_plain_color}"').replace('stroke="white"', "stroke=#444")
132
+ if opts.forge_canvas_toolbar_always:
133
+ canvas_html_uuid = canvas_html_uuid.replace('class="forge-toolbar"', 'class="forge-toolbar-static"')
134
+
135
+ self.block = gr.HTML(canvas_html_uuid, visible=visible, elem_id=elem_id, elem_classes=elem_classes)
136
+ self.foreground = LogicalImage(visible=DEBUG_MODE, label="foreground", numpy=numpy, elem_id=self.uuid, elem_classes=["logical_image_foreground"])
137
+ self.background = LogicalImage(visible=DEBUG_MODE, label="background", numpy=numpy, value=initial_image, elem_id=self.uuid, elem_classes=["logical_image_background"])
138
+ Context.root_block.load(None, js=f'async ()=>{{new ForgeCanvas("{self.uuid}", {no_upload}, {no_scribbles}, {contrast_scribbles}, {height or opts.forge_canvas_height}, ' f"'{scribble_color}', {scribble_color_fixed}, {scribble_width}, {scribble_width_fixed}, {opts.forge_canvas_consistent_brush}, " f"{scribble_alpha}, {scribble_alpha_fixed}, {scribble_softness}, {scribble_softness_fixed});}}")
modules_forge/forge_version.py ADDED
@@ -0,0 +1 @@
 
 
1
+ version = "neo"
modules_forge/initialization.py ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+
4
+ from modules.timer import startup_timer
5
+
6
+ INITIALIZED = False
7
+
8
+
9
+ def initialize_forge():
10
+ global INITIALIZED
11
+ if INITIALIZED:
12
+ return
13
+
14
+ INITIALIZED = True
15
+
16
+ sys.path.insert(0, os.path.join(os.path.dirname(os.path.dirname(__file__)), "modules_forge", "packages"))
17
+
18
+ from backend.args import args
19
+
20
+ if args.gpu_device_id is not None:
21
+ os.environ["CUDA_VISIBLE_DEVICES"] = str(args.gpu_device_id)
22
+ print("Set device to:", args.gpu_device_id)
23
+
24
+ if args.cuda_malloc:
25
+ from modules_forge.cuda_malloc import try_cuda_malloc
26
+
27
+ try_cuda_malloc()
28
+ startup_timer.record("cuda_malloc")
29
+
30
+ from backend import memory_management
31
+
32
+ startup_timer.record("memory_management")
33
+
34
+ import torch
35
+ import torchvision # noqa: F401
36
+
37
+ startup_timer.record("import torch")
38
+
39
+ device = memory_management.get_torch_device()
40
+ torch.zeros((1, 1)).to(device, torch.float32)
41
+ memory_management.soft_empty_cache()
42
+
43
+ startup_timer.record("tensor warmup")
44
+
45
+ from backend import stream
46
+
47
+ print("CUDA Using Stream:", stream.should_use_stream())
48
+
49
+ startup_timer.record("stream")
50
+
51
+ from modules_forge.shared import diffusers_dir
52
+
53
+ if "HF_HOME" not in os.environ:
54
+ os.environ["HF_HOME"] = diffusers_dir
55
+
56
+ if "HF_DATASETS_CACHE" not in os.environ:
57
+ os.environ["HF_DATASETS_CACHE"] = diffusers_dir
58
+
59
+ if "HUGGINGFACE_HUB_CACHE" not in os.environ:
60
+ os.environ["HUGGINGFACE_HUB_CACHE"] = diffusers_dir
61
+
62
+ if "HUGGINGFACE_ASSETS_CACHE" not in os.environ:
63
+ os.environ["HUGGINGFACE_ASSETS_CACHE"] = diffusers_dir
64
+
65
+ if "HF_HUB_CACHE" not in os.environ:
66
+ os.environ["HF_HUB_CACHE"] = diffusers_dir
67
+
68
+ startup_timer.record("diffusers_dir")
69
+
70
+ from modules_forge import patch_basic
71
+
72
+ patch_basic.patch_all_basics()
73
+
74
+ startup_timer.record("patch basics")
75
+
76
+ from backend.huggingface import process
77
+
78
+ process()
79
+
80
+ startup_timer.record("decompress tokenizers")
modules_forge/main_entry.py ADDED
@@ -0,0 +1,343 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ import gradio as gr
4
+ import torch
5
+ from gradio.context import Context
6
+
7
+ from backend import memory_management, operations, stream
8
+ from backend.args import dynamic_args
9
+ from modules import infotext_utils, paths, processing, sd_models, shared, shared_items, ui_common
10
+
11
+ total_vram = int(memory_management.total_vram)
12
+
13
+ ui_forge_preset: gr.Radio = None
14
+
15
+ ui_checkpoint: gr.Dropdown = None
16
+ ui_vae: gr.Dropdown = None
17
+ ui_clip_skip: gr.Slider = None
18
+
19
+ ui_forge_unet_storage_dtype_options: gr.Radio = None
20
+ ui_forge_async_loading: gr.Radio = None
21
+ ui_forge_pin_shared_memory: gr.Radio = None
22
+ ui_forge_inference_memory: gr.Slider = None
23
+
24
+
25
+ forge_unet_storage_dtype_options = {
26
+ "Automatic": (None, False),
27
+ "Automatic (fp16 LoRA)": (None, True),
28
+ "float8-e4m3fn": (torch.float8_e4m3fn, False),
29
+ "float8-e4m3fn (fp16 LoRA)": (torch.float8_e4m3fn, True),
30
+ }
31
+
32
+ bnb_storage_dtype_options = {
33
+ "bnb-nf4": ("nf4", False),
34
+ "bnb-nf4 (fp16 LoRA)": ("nf4", True),
35
+ "bnb-fp4": ("fp4", False),
36
+ "bnb-fp4 (fp16 LoRA)": ("fp4", True),
37
+ }
38
+
39
+ if operations.bnb_available:
40
+ forge_unet_storage_dtype_options.update(bnb_storage_dtype_options)
41
+
42
+ module_list = {}
43
+
44
+
45
+ def bind_to_opts(comp, k, save=False, callback=None):
46
+ def on_change(v):
47
+ shared.opts.set(k, v)
48
+ if save:
49
+ shared.opts.save(shared.config_filename)
50
+ if callback is not None:
51
+ callback()
52
+
53
+ comp.change(on_change, inputs=[comp], queue=False, show_progress=False)
54
+
55
+
56
+ def make_checkpoint_manager_ui():
57
+ global ui_checkpoint, ui_vae, ui_clip_skip, ui_forge_unet_storage_dtype_options, ui_forge_async_loading, ui_forge_pin_shared_memory, ui_forge_inference_memory, ui_forge_preset
58
+
59
+ if shared.opts.sd_model_checkpoint in [None, "None", "none", ""]:
60
+ if len(sd_models.checkpoints_list) == 0:
61
+ sd_models.list_models()
62
+ if len(sd_models.checkpoints_list) > 0:
63
+ shared.opts.set("sd_model_checkpoint", next(iter(sd_models.checkpoints_list.values())).name)
64
+
65
+ ui_forge_preset = gr.Radio(label="UI Preset", value=lambda: shared.opts.forge_preset, choices=("sd", "xl", "flux", "qwen", "lumina", "wan"), elem_id="forge_ui_preset")
66
+
67
+ ui_checkpoint = gr.Dropdown(label="Checkpoint", value=None, choices=None, elem_id="setting_sd_model_checkpoint", elem_classes=["model_selection"])
68
+
69
+ ui_vae = gr.Dropdown(label="VAE / Text Encoder", value=None, choices=None, multiselect=True)
70
+
71
+ def gr_refresh_models():
72
+ ckpt_list, vae_list = refresh_models()
73
+ return gr.update(choices=ckpt_list), gr.update(choices=vae_list)
74
+
75
+ refresh_button = ui_common.ToolButton(value=ui_common.refresh_symbol, elem_id="forge_refresh_checkpoint", tooltip="Refresh")
76
+ refresh_button.click(fn=gr_refresh_models, outputs=[ui_checkpoint, ui_vae], queue=False)
77
+
78
+ def gr_refresh_on_load():
79
+ ckpt_list, vae_list = refresh_models()
80
+ refresh_memory_management_settings()
81
+ return [gr.update(value=shared.opts.sd_model_checkpoint, choices=ckpt_list), gr.update(value=[os.path.basename(x) for x in shared.opts.forge_additional_modules], choices=vae_list)]
82
+
83
+ Context.root_block.load(fn=gr_refresh_on_load, outputs=[ui_checkpoint, ui_vae], show_progress=False, queue=False)
84
+
85
+ ui_forge_unet_storage_dtype_options = gr.Dropdown(label="Diffusion in Low Bits", value=lambda: shared.opts.forge_unet_storage_dtype, choices=list(forge_unet_storage_dtype_options.keys()))
86
+ bind_to_opts(ui_forge_unet_storage_dtype_options, "forge_unet_storage_dtype", save=True, callback=refresh_model_loading_parameters)
87
+
88
+ ui_forge_async_loading = gr.Radio(label="Swap Method", value=lambda: shared.opts.forge_async_loading, choices=["Queue", "Async"])
89
+ ui_forge_pin_shared_memory = gr.Radio(label="Swap Location", value=lambda: shared.opts.forge_pin_shared_memory, choices=["CPU", "Shared"])
90
+ ui_forge_inference_memory = gr.Slider(label="GPU Weights (MB)", value=lambda: total_vram - shared.opts.forge_inference_memory, minimum=0, maximum=int(memory_management.total_vram), step=1)
91
+
92
+ mem_comps = [ui_forge_inference_memory, ui_forge_async_loading, ui_forge_pin_shared_memory]
93
+
94
+ ui_forge_inference_memory.change(ui_refresh_memory_management_settings, inputs=mem_comps, queue=False, show_progress=False)
95
+ ui_forge_async_loading.change(ui_refresh_memory_management_settings, inputs=mem_comps, queue=False, show_progress=False)
96
+ ui_forge_pin_shared_memory.change(ui_refresh_memory_management_settings, inputs=mem_comps, queue=False, show_progress=False)
97
+
98
+ ui_clip_skip = gr.Slider(label="Clip Skip", value=lambda: shared.opts.CLIP_stop_at_last_layers, minimum=1, maximum=12, step=1)
99
+ bind_to_opts(ui_clip_skip, "CLIP_stop_at_last_layers", save=True)
100
+
101
+ ui_checkpoint.change(checkpoint_change, inputs=[ui_checkpoint, ui_forge_preset], show_progress=False)
102
+ ui_vae.change(modules_change, inputs=[ui_vae, ui_forge_preset], queue=False, show_progress=False)
103
+
104
+
105
+ def find_files_with_extensions(base_path, extensions):
106
+ found_files = {}
107
+ for root, _, files in os.walk(base_path):
108
+ for file in files:
109
+ if any(file.endswith(ext) for ext in extensions):
110
+ full_path = os.path.join(root, file)
111
+ found_files[file] = full_path
112
+ return found_files
113
+
114
+
115
+ def refresh_models():
116
+ global module_list
117
+
118
+ shared_items.refresh_checkpoints()
119
+ ckpt_list = shared_items.list_checkpoint_tiles(shared.opts.sd_checkpoint_dropdown_use_short)
120
+
121
+ file_extensions = ("ckpt", "pt", "pth", "bin", "safetensors", "sft", "gguf")
122
+
123
+ module_list.clear()
124
+
125
+ module_paths: set[str] = {
126
+ os.path.abspath(os.path.join(paths.models_path, "VAE")),
127
+ os.path.abspath(os.path.join(paths.models_path, "text_encoder")),
128
+ *shared.cmd_opts.vae_dirs,
129
+ *shared.cmd_opts.text_encoder_dirs,
130
+ }
131
+
132
+ for vae_path in module_paths:
133
+ vae_files = find_files_with_extensions(vae_path, file_extensions)
134
+ module_list.update(vae_files)
135
+
136
+ return sorted(ckpt_list), sorted(module_list.keys())
137
+
138
+
139
+ def ui_refresh_memory_management_settings(model_memory, async_loading, pin_shared_memory):
140
+ """Pass calculated `model_memory` from "GPU Weights" UI slider"""
141
+ refresh_memory_management_settings(async_loading=async_loading, pin_shared_memory=pin_shared_memory, model_memory=model_memory) # Use model_memory directly from UI slider value
142
+
143
+
144
+ def refresh_memory_management_settings(async_loading=None, inference_memory=None, pin_shared_memory=None, model_memory=None):
145
+ # Fallback to defaults if values are not passed
146
+ async_loading = async_loading if async_loading is not None else shared.opts.forge_async_loading
147
+ inference_memory = inference_memory if inference_memory is not None else shared.opts.forge_inference_memory
148
+ pin_shared_memory = pin_shared_memory if pin_shared_memory is not None else shared.opts.forge_pin_shared_memory
149
+
150
+ # If model_memory is provided, calculate inference memory accordingly, otherwise use inference_memory directly
151
+ if model_memory is None:
152
+ model_memory = total_vram - inference_memory
153
+ else:
154
+ inference_memory = total_vram - model_memory
155
+
156
+ shared.opts.set("forge_async_loading", async_loading)
157
+ shared.opts.set("forge_inference_memory", inference_memory)
158
+ shared.opts.set("forge_pin_shared_memory", pin_shared_memory)
159
+
160
+ stream.stream_activated = async_loading == "Async"
161
+ memory_management.current_inference_memory = inference_memory * 1024 * 1024 # Convert MB to bytes
162
+ memory_management.PIN_SHARED_MEMORY = pin_shared_memory == "Shared"
163
+
164
+ log_dict = dict(stream=stream.should_use_stream(), inference_memory=memory_management.minimum_inference_memory() / (1024 * 1024), pin_shared_memory=memory_management.PIN_SHARED_MEMORY)
165
+
166
+ print(f"Environment vars changed: {log_dict}")
167
+
168
+ if inference_memory < min(512, total_vram * 0.05):
169
+ print("------------------")
170
+ print(f"[Low VRAM Warning] You just set Forge to use 100% GPU memory ({model_memory:.2f} MB) to load model weights.")
171
+ print("[Low VRAM Warning] This means you will have 0% GPU memory (0.00 MB) to do matrix computation. Computations may fallback to CPU or go Out of Memory.")
172
+ print("[Low VRAM Warning] In many cases, image generation will be 10x slower.")
173
+ print("[Low VRAM Warning] To solve the problem, you can set the 'GPU Weights' (on the top of page) to a lower value.")
174
+ print("[Low VRAM Warning] If you cannot find 'GPU Weights', you can click the 'all' option in the 'UI' area on the left-top corner of the webpage.")
175
+ print("[Low VRAM Warning] Make sure that you know what you are testing.")
176
+ print("------------------")
177
+ else:
178
+ compute_percentage = (inference_memory / total_vram) * 100.0
179
+ print(f"[GPU Setting] You will use {(100 - compute_percentage):.2f}% GPU memory ({model_memory:.2f} MB) to load weights, and use {compute_percentage:.2f}% GPU memory ({inference_memory:.2f} MB) to do matrix computation.")
180
+
181
+ processing.need_global_unload = True
182
+
183
+
184
+ def refresh_model_loading_parameters():
185
+ from modules.sd_models import model_data, select_checkpoint
186
+
187
+ checkpoint_info = select_checkpoint()
188
+
189
+ unet_storage_dtype, lora_fp16 = forge_unet_storage_dtype_options.get(shared.opts.forge_unet_storage_dtype, (None, False))
190
+
191
+ dynamic_args["online_lora"] = lora_fp16
192
+
193
+ model_data.forge_loading_parameters = dict(checkpoint_info=checkpoint_info, additional_modules=shared.opts.forge_additional_modules, unet_storage_dtype=unet_storage_dtype)
194
+
195
+ print(f"Model selected: {model_data.forge_loading_parameters}")
196
+ print(f"Using online LoRAs in FP16: {lora_fp16}")
197
+ processing.need_global_unload = True
198
+
199
+
200
+ def checkpoint_change(ckpt_name: str, preset: str, save=True, refresh=True) -> bool:
201
+ """`ckpt_name` accepts valid aliases; returns `True` if checkpoint changed"""
202
+ new_ckpt_info = sd_models.get_closet_checkpoint_match(ckpt_name)
203
+ current_ckpt_info = sd_models.get_closet_checkpoint_match(shared.opts.data.get("sd_model_checkpoint", ""))
204
+ if new_ckpt_info == current_ckpt_info:
205
+ return False
206
+
207
+ shared.opts.set("sd_model_checkpoint", ckpt_name)
208
+ if preset is not None:
209
+ shared.opts.set(f"forge_checkpoint_{preset}", ckpt_name)
210
+
211
+ if save:
212
+ shared.opts.save(shared.config_filename)
213
+ if refresh:
214
+ refresh_model_loading_parameters()
215
+ return True
216
+
217
+
218
+ def modules_change(module_values: list, preset: str, save=True, refresh=True) -> bool:
219
+ """`module_values` accepts file paths or just the module names; returns `True` if modules changed"""
220
+ modules = []
221
+ for v in module_values:
222
+ module_name = os.path.basename(v) # If the input is a filepath, extract the file name
223
+ if module_name in module_list:
224
+ modules.append(module_list[module_name])
225
+
226
+ # skip further processing if value unchanged
227
+ if sorted(modules) == sorted(shared.opts.data.get("forge_additional_modules", [])):
228
+ return False
229
+
230
+ shared.opts.set("forge_additional_modules", modules)
231
+ if preset is not None:
232
+ shared.opts.set(f"forge_additional_modules_{preset}", modules)
233
+
234
+ if save:
235
+ shared.opts.save(shared.config_filename)
236
+ if refresh:
237
+ refresh_model_loading_parameters()
238
+ return True
239
+
240
+
241
+ def get_a1111_ui_component(tab, label):
242
+ fields = infotext_utils.paste_fields[tab]["fields"]
243
+ for f in fields:
244
+ if f.label == label or f.api == label:
245
+ return f.component
246
+
247
+
248
+ def forge_main_entry():
249
+ ui_txt2img_width = get_a1111_ui_component("txt2img", "Size-1")
250
+ ui_txt2img_height = get_a1111_ui_component("txt2img", "Size-2")
251
+ ui_txt2img_cfg = get_a1111_ui_component("txt2img", "CFG scale")
252
+ ui_txt2img_distilled_cfg = get_a1111_ui_component("txt2img", "Distilled CFG Scale")
253
+ ui_txt2img_sampler = get_a1111_ui_component("txt2img", "sampler_name")
254
+ ui_txt2img_scheduler = get_a1111_ui_component("txt2img", "scheduler")
255
+
256
+ ui_img2img_width = get_a1111_ui_component("img2img", "Size-1")
257
+ ui_img2img_height = get_a1111_ui_component("img2img", "Size-2")
258
+ ui_img2img_cfg = get_a1111_ui_component("img2img", "CFG scale")
259
+ ui_img2img_distilled_cfg = get_a1111_ui_component("img2img", "Distilled CFG Scale")
260
+ ui_img2img_sampler = get_a1111_ui_component("img2img", "sampler_name")
261
+ ui_img2img_scheduler = get_a1111_ui_component("img2img", "scheduler")
262
+
263
+ ui_txt2img_hr_cfg = get_a1111_ui_component("txt2img", "Hires CFG Scale")
264
+ ui_txt2img_hr_distilled_cfg = get_a1111_ui_component("txt2img", "Hires Distilled CFG Scale")
265
+
266
+ ui_txt2img_batch_size = get_a1111_ui_component("txt2img", "Batch size")
267
+ ui_img2img_batch_size = get_a1111_ui_component("img2img", "Batch size")
268
+
269
+ output_targets = [
270
+ ui_checkpoint,
271
+ ui_vae,
272
+ ui_clip_skip,
273
+ ui_forge_unet_storage_dtype_options,
274
+ ui_forge_async_loading,
275
+ ui_forge_pin_shared_memory,
276
+ ui_forge_inference_memory,
277
+ ui_txt2img_width,
278
+ ui_img2img_width,
279
+ ui_txt2img_height,
280
+ ui_img2img_height,
281
+ ui_txt2img_cfg,
282
+ ui_img2img_cfg,
283
+ ui_txt2img_distilled_cfg,
284
+ ui_img2img_distilled_cfg,
285
+ ui_txt2img_sampler,
286
+ ui_img2img_sampler,
287
+ ui_txt2img_scheduler,
288
+ ui_img2img_scheduler,
289
+ ui_txt2img_hr_cfg,
290
+ ui_txt2img_hr_distilled_cfg,
291
+ ui_txt2img_batch_size,
292
+ ui_img2img_batch_size,
293
+ ]
294
+
295
+ ui_forge_preset.change(on_preset_change, inputs=[ui_forge_preset], outputs=output_targets, queue=False, show_progress=False).then(js="clickLoraRefresh", fn=None, queue=False, show_progress=False)
296
+ Context.root_block.load(on_preset_change, inputs=[ui_forge_preset], outputs=output_targets, queue=False, show_progress=False)
297
+
298
+ refresh_model_loading_parameters()
299
+
300
+
301
+ def on_preset_change(preset: str):
302
+ assert preset is not None
303
+ shared.opts.set("forge_preset", preset)
304
+ shared.opts.save(shared.config_filename)
305
+
306
+ model_mem = getattr(shared.opts, f"{preset}_gpu_mb", total_vram - 1024)
307
+ if model_mem < 0 or model_mem > total_vram:
308
+ model_mem = total_vram - 1024
309
+
310
+ show_clip_skip = preset not in ("qwen", "lumina", "wan")
311
+ show_basic_mem = preset != "sd"
312
+ show_adv_mem = preset in ("flux", "qwen", "wan")
313
+ distilled = preset in ("flux", "lumina", "wan")
314
+ d_label = "Distilled CFG Scale" if preset == "flux" else "Shift"
315
+ batch_args = {"minimum": 1, "maximum": 97, "step": 16, "label": "Frames", "value": 1} if preset == "wan" else {"minimum": 1, "maximum": 8, "step": 1, "label": "Batch size", "value": 1}
316
+
317
+ additional_modules = [os.path.basename(x) for x in getattr(shared.opts, f"forge_additional_modules_{preset}", [])]
318
+
319
+ return [
320
+ gr.update(value=getattr(shared.opts, f"forge_checkpoint_{preset}", shared.opts.sd_model_checkpoint)), # ui_checkpoint
321
+ gr.update(value=additional_modules), # ui_vae
322
+ gr.update(visible=show_clip_skip, value=getattr(shared.opts, "CLIP_stop_at_last_layers", 2)), # ui_clip_skip
323
+ gr.update(visible=show_basic_mem, value=getattr(shared.opts, "forge_unet_storage_dtype", "Automatic")), # ui_forge_unet_storage_dtype_options
324
+ gr.update(visible=show_adv_mem, value=getattr(shared.opts, "forge_async_loading", "Queue")), # ui_forge_async_loading
325
+ gr.update(visible=show_adv_mem, value=getattr(shared.opts, "forge_pin_shared_memory", "CPU")), # ui_forge_pin_shared_memory
326
+ gr.update(visible=show_basic_mem, value=model_mem), # ui_forge_inference_memory
327
+ gr.update(value=getattr(shared.opts, f"{preset}_t2i_width", 768)), # ui_txt2img_width
328
+ gr.update(value=getattr(shared.opts, f"{preset}_i2i_width", 768)), # ui_img2img_width
329
+ gr.update(value=getattr(shared.opts, f"{preset}_t2i_height", 768)), # ui_txt2img_height
330
+ gr.update(value=getattr(shared.opts, f"{preset}_i2i_height", 768)), # ui_img2img_height
331
+ gr.update(value=getattr(shared.opts, f"{preset}_t2i_cfg", 1.0)), # ui_txt2img_cfg
332
+ gr.update(value=getattr(shared.opts, f"{preset}_i2i_cfg", 1.0)), # ui_img2img_cfg
333
+ gr.update(visible=distilled, label=d_label, value=getattr(shared.opts, f"{preset}_t2i_d_cfg", 3.0)), # ui_txt2img_distilled_cfg
334
+ gr.update(visible=distilled, label=d_label, value=getattr(shared.opts, f"{preset}_i2i_d_cfg", 3.0)), # ui_img2img_distilled_cfg
335
+ gr.update(value=getattr(shared.opts, f"{preset}_t2i_sampler", "Euler")), # ui_txt2img_sampler
336
+ gr.update(value=getattr(shared.opts, f"{preset}_i2i_sampler", "Euler")), # ui_img2img_sampler
337
+ gr.update(value=getattr(shared.opts, f"{preset}_t2i_scheduler", "Simple")), # ui_txt2img_scheduler
338
+ gr.update(value=getattr(shared.opts, f"{preset}_i2i_scheduler", "Simple")), # ui_img2img_scheduler
339
+ gr.update(value=getattr(shared.opts, f"{preset}_t2i_hr_cfg", 1.0)), # ui_txt2img_hr_cfg
340
+ gr.update(visible=distilled, label=d_label, value=getattr(shared.opts, f"{preset}_t2i_hr_d_cfg", 3.0)), # ui_txt2img_hr_distilled_cfg
341
+ gr.update(**batch_args), # ui_txt2img_batch_size
342
+ gr.update(**batch_args), # ui_img2img_batch_size
343
+ ]
modules_forge/main_thread.py ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is the main thread that handles all gradio calls for major t2i or i2i processing.
2
+ # Other gradio calls (like those from extensions) are not influenced.
3
+ # By using one single thread to process all major calls, model moving is significantly faster.
4
+
5
+
6
+ import time
7
+ import traceback
8
+ import threading
9
+
10
+
11
+ lock = threading.Lock()
12
+ last_id = 0
13
+ waiting_list = []
14
+ finished_list = []
15
+ last_exception = None
16
+
17
+
18
+ class Task:
19
+ def __init__(self, task_id, func, args, kwargs):
20
+ self.task_id = task_id
21
+ self.func = func
22
+ self.args = args
23
+ self.kwargs = kwargs
24
+ self.result = None
25
+ self.exception = None
26
+
27
+ def work(self):
28
+ global last_exception
29
+ try:
30
+ self.result = self.func(*self.args, **self.kwargs)
31
+ self.exception = None
32
+ last_exception = None
33
+ except Exception as e:
34
+ traceback.print_exc()
35
+ print(e)
36
+ self.exception = e
37
+ last_exception = e
38
+
39
+
40
+ def loop():
41
+ global lock, last_id, waiting_list, finished_list
42
+ while True:
43
+ time.sleep(0.01)
44
+ if len(waiting_list) > 0:
45
+ with lock:
46
+ task = waiting_list.pop(0)
47
+
48
+ task.work()
49
+
50
+ with lock:
51
+ finished_list.append(task)
52
+
53
+
54
+ def async_run(func, *args, **kwargs):
55
+ global lock, last_id, waiting_list, finished_list
56
+ with lock:
57
+ last_id += 1
58
+ new_task = Task(task_id=last_id, func=func, args=args, kwargs=kwargs)
59
+ waiting_list.append(new_task)
60
+ return new_task.task_id
61
+
62
+
63
+ def run_and_wait_result(func, *args, **kwargs):
64
+ global lock, last_id, waiting_list, finished_list
65
+ current_id = async_run(func, *args, **kwargs)
66
+ while True:
67
+ time.sleep(0.01)
68
+ finished_task = None
69
+ for t in finished_list.copy(): # thread safe shallow copy without needing a lock
70
+ if t.task_id == current_id:
71
+ finished_task = t
72
+ break
73
+ if finished_task is not None:
74
+ with lock:
75
+ finished_list.remove(finished_task)
76
+ return finished_task.result
77
+
modules_forge/packages/comfy/LICENSE ADDED
@@ -0,0 +1,674 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ GNU GENERAL PUBLIC LICENSE
2
+ Version 3, 29 June 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 General Public License is a free, copyleft license for
11
+ software and other kinds of works.
12
+
13
+ The licenses for most software and other practical works are designed
14
+ to take away your freedom to share and change the works. By contrast,
15
+ the GNU General Public License is intended to guarantee your freedom to
16
+ share and change all versions of a program--to make sure it remains free
17
+ software for all its users. We, the Free Software Foundation, use the
18
+ GNU General Public License for most of our software; it applies also to
19
+ any other work released this way by its authors. You can apply it to
20
+ your programs, too.
21
+
22
+ When we speak of free software, we are referring to freedom, not
23
+ price. Our General Public Licenses are designed to make sure that you
24
+ have the freedom to distribute copies of free software (and charge for
25
+ them if you wish), that you receive source code or can get it if you
26
+ want it, that you can change the software or use pieces of it in new
27
+ free programs, and that you know you can do these things.
28
+
29
+ To protect your rights, we need to prevent others from denying you
30
+ these rights or asking you to surrender the rights. Therefore, you have
31
+ certain responsibilities if you distribute copies of the software, or if
32
+ you modify it: responsibilities to respect the freedom of others.
33
+
34
+ For example, if you distribute copies of such a program, whether
35
+ gratis or for a fee, you must pass on to the recipients the same
36
+ freedoms that you received. You must make sure that they, too, receive
37
+ or can get the source code. And you must show them these terms so they
38
+ know their rights.
39
+
40
+ Developers that use the GNU GPL protect your rights with two steps:
41
+ (1) assert copyright on the software, and (2) offer you this License
42
+ giving you legal permission to copy, distribute and/or modify it.
43
+
44
+ For the developers' and authors' protection, the GPL clearly explains
45
+ that there is no warranty for this free software. For both users' and
46
+ authors' sake, the GPL requires that modified versions be marked as
47
+ changed, so that their problems will not be attributed erroneously to
48
+ authors of previous versions.
49
+
50
+ Some devices are designed to deny users access to install or run
51
+ modified versions of the software inside them, although the manufacturer
52
+ can do so. This is fundamentally incompatible with the aim of
53
+ protecting users' freedom to change the software. The systematic
54
+ pattern of such abuse occurs in the area of products for individuals to
55
+ use, which is precisely where it is most unacceptable. Therefore, we
56
+ have designed this version of the GPL to prohibit the practice for those
57
+ products. If such problems arise substantially in other domains, we
58
+ stand ready to extend this provision to those domains in future versions
59
+ of the GPL, as needed to protect the freedom of users.
60
+
61
+ Finally, every program is threatened constantly by software patents.
62
+ States should not allow patents to restrict development and use of
63
+ software on general-purpose computers, but in those that do, we wish to
64
+ avoid the special danger that patents applied to a free program could
65
+ make it effectively proprietary. To prevent this, the GPL assures that
66
+ patents cannot be used to render the program non-free.
67
+
68
+ The precise terms and conditions for copying, distribution and
69
+ modification follow.
70
+
71
+ TERMS AND CONDITIONS
72
+
73
+ 0. Definitions.
74
+
75
+ "This License" refers to version 3 of the GNU General Public License.
76
+
77
+ "Copyright" also means copyright-like laws that apply to other kinds of
78
+ works, such as semiconductor masks.
79
+
80
+ "The Program" refers to any copyrightable work licensed under this
81
+ License. Each licensee is addressed as "you". "Licensees" and
82
+ "recipients" may be individuals or organizations.
83
+
84
+ To "modify" a work means to copy from or adapt all or part of the work
85
+ in a fashion requiring copyright permission, other than the making of an
86
+ exact copy. The resulting work is called a "modified version" of the
87
+ earlier work or a work "based on" the earlier work.
88
+
89
+ A "covered work" means either the unmodified Program or a work based
90
+ on the Program.
91
+
92
+ To "propagate" a work means to do anything with it that, without
93
+ permission, would make you directly or secondarily liable for
94
+ infringement under applicable copyright law, except executing it on a
95
+ computer or modifying a private copy. Propagation includes copying,
96
+ distribution (with or without modification), making available to the
97
+ public, and in some countries other activities as well.
98
+
99
+ To "convey" a work means any kind of propagation that enables other
100
+ parties to make or receive copies. Mere interaction with a user through
101
+ a computer network, with no transfer of a copy, is not conveying.
102
+
103
+ An interactive user interface displays "Appropriate Legal Notices"
104
+ to the extent that it includes a convenient and prominently visible
105
+ feature that (1) displays an appropriate copyright notice, and (2)
106
+ tells the user that there is no warranty for the work (except to the
107
+ extent that warranties are provided), that licensees may convey the
108
+ work under this License, and how to view a copy of this License. If
109
+ the interface presents a list of user commands or options, such as a
110
+ menu, a prominent item in the list meets this criterion.
111
+
112
+ 1. Source Code.
113
+
114
+ The "source code" for a work means the preferred form of the work
115
+ for making modifications to it. "Object code" means any non-source
116
+ form of a work.
117
+
118
+ A "Standard Interface" means an interface that either is an official
119
+ standard defined by a recognized standards body, or, in the case of
120
+ interfaces specified for a particular programming language, one that
121
+ is widely used among developers working in that language.
122
+
123
+ The "System Libraries" of an executable work include anything, other
124
+ than the work as a whole, that (a) is included in the normal form of
125
+ packaging a Major Component, but which is not part of that Major
126
+ Component, and (b) serves only to enable use of the work with that
127
+ Major Component, or to implement a Standard Interface for which an
128
+ implementation is available to the public in source code form. A
129
+ "Major Component", in this context, means a major essential component
130
+ (kernel, window system, and so on) of the specific operating system
131
+ (if any) on which the executable work runs, or a compiler used to
132
+ produce the work, or an object code interpreter used to run it.
133
+
134
+ The "Corresponding Source" for a work in object code form means all
135
+ the source code needed to generate, install, and (for an executable
136
+ work) run the object code and to modify the work, including scripts to
137
+ control those activities. However, it does not include the work's
138
+ System Libraries, or general-purpose tools or generally available free
139
+ programs which are used unmodified in performing those activities but
140
+ which are not part of the work. For example, Corresponding Source
141
+ includes interface definition files associated with source files for
142
+ the work, and the source code for shared libraries and dynamically
143
+ linked subprograms that the work is specifically designed to require,
144
+ such as by intimate data communication or control flow between those
145
+ subprograms and other parts of the work.
146
+
147
+ The Corresponding Source need not include anything that users
148
+ can regenerate automatically from other parts of the Corresponding
149
+ Source.
150
+
151
+ The Corresponding Source for a work in source code form is that
152
+ same work.
153
+
154
+ 2. Basic Permissions.
155
+
156
+ All rights granted under this License are granted for the term of
157
+ copyright on the Program, and are irrevocable provided the stated
158
+ conditions are met. This License explicitly affirms your unlimited
159
+ permission to run the unmodified Program. The output from running a
160
+ covered work is covered by this License only if the output, given its
161
+ content, constitutes a covered work. This License acknowledges your
162
+ rights of fair use or other equivalent, as provided by copyright law.
163
+
164
+ You may make, run and propagate covered works that you do not
165
+ convey, without conditions so long as your license otherwise remains
166
+ in force. You may convey covered works to others for the sole purpose
167
+ of having them make modifications exclusively for you, or provide you
168
+ with facilities for running those works, provided that you comply with
169
+ the terms of this License in conveying all material for which you do
170
+ not control copyright. Those thus making or running the covered works
171
+ for you must do so exclusively on your behalf, under your direction
172
+ and control, on terms that prohibit them from making any copies of
173
+ your copyrighted material outside their relationship with you.
174
+
175
+ Conveying under any other circumstances is permitted solely under
176
+ the conditions stated below. Sublicensing is not allowed; section 10
177
+ makes it unnecessary.
178
+
179
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180
+
181
+ No covered work shall be deemed part of an effective technological
182
+ measure under any applicable law fulfilling obligations under article
183
+ 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184
+ similar laws prohibiting or restricting circumvention of such
185
+ measures.
186
+
187
+ When you convey a covered work, you waive any legal power to forbid
188
+ circumvention of technological measures to the extent such circumvention
189
+ is effected by exercising rights under this License with respect to
190
+ the covered work, and you disclaim any intention to limit operation or
191
+ modification of the work as a means of enforcing, against the work's
192
+ users, your or third parties' legal rights to forbid circumvention of
193
+ technological measures.
194
+
195
+ 4. Conveying Verbatim Copies.
196
+
197
+ You may convey verbatim copies of the Program's source code as you
198
+ receive it, in any medium, provided that you conspicuously and
199
+ appropriately publish on each copy an appropriate copyright notice;
200
+ keep intact all notices stating that this License and any
201
+ non-permissive terms added in accord with section 7 apply to the code;
202
+ keep intact all notices of the absence of any warranty; and give all
203
+ recipients a copy of this License along with the Program.
204
+
205
+ You may charge any price or no price for each copy that you convey,
206
+ and you may offer support or warranty protection for a fee.
207
+
208
+ 5. Conveying Modified Source Versions.
209
+
210
+ You may convey a work based on the Program, or the modifications to
211
+ produce it from the Program, in the form of source code under the
212
+ terms of section 4, provided that you also meet all of these conditions:
213
+
214
+ a) The work must carry prominent notices stating that you modified
215
+ it, and giving a relevant date.
216
+
217
+ b) The work must carry prominent notices stating that it is
218
+ released under this License and any conditions added under section
219
+ 7. This requirement modifies the requirement in section 4 to
220
+ "keep intact all notices".
221
+
222
+ c) You must license the entire work, as a whole, under this
223
+ License to anyone who comes into possession of a copy. This
224
+ License will therefore apply, along with any applicable section 7
225
+ additional terms, to the whole of the work, and all its parts,
226
+ regardless of how they are packaged. This License gives no
227
+ permission to license the work in any other way, but it does not
228
+ invalidate such permission if you have separately received it.
229
+
230
+ d) If the work has interactive user interfaces, each must display
231
+ Appropriate Legal Notices; however, if the Program has interactive
232
+ interfaces that do not display Appropriate Legal Notices, your
233
+ work need not make them do so.
234
+
235
+ A compilation of a covered work with other separate and independent
236
+ works, which are not by their nature extensions of the covered work,
237
+ and which are not combined with it such as to form a larger program,
238
+ in or on a volume of a storage or distribution medium, is called an
239
+ "aggregate" if the compilation and its resulting copyright are not
240
+ used to limit the access or legal rights of the compilation's users
241
+ beyond what the individual works permit. Inclusion of a covered work
242
+ in an aggregate does not cause this License to apply to the other
243
+ parts of the aggregate.
244
+
245
+ 6. Conveying Non-Source Forms.
246
+
247
+ You may convey a covered work in object code form under the terms
248
+ of sections 4 and 5, provided that you also convey the
249
+ machine-readable Corresponding Source under the terms of this License,
250
+ in one of these ways:
251
+
252
+ a) Convey the object code in, or embodied in, a physical product
253
+ (including a physical distribution medium), accompanied by the
254
+ Corresponding Source fixed on a durable physical medium
255
+ customarily used for software interchange.
256
+
257
+ b) Convey the object code in, or embodied in, a physical product
258
+ (including a physical distribution medium), accompanied by a
259
+ written offer, valid for at least three years and valid for as
260
+ long as you offer spare parts or customer support for that product
261
+ model, to give anyone who possesses the object code either (1) a
262
+ copy of the Corresponding Source for all the software in the
263
+ product that is covered by this License, on a durable physical
264
+ medium customarily used for software interchange, for a price no
265
+ more than your reasonable cost of physically performing this
266
+ conveying of source, or (2) access to copy the
267
+ Corresponding Source from a network server at no charge.
268
+
269
+ c) Convey individual copies of the object code with a copy of the
270
+ written offer to provide the Corresponding Source. This
271
+ alternative is allowed only occasionally and noncommercially, and
272
+ only if you received the object code with such an offer, in accord
273
+ with subsection 6b.
274
+
275
+ d) Convey the object code by offering access from a designated
276
+ place (gratis or for a charge), and offer equivalent access to the
277
+ Corresponding Source in the same way through the same place at no
278
+ further charge. You need not require recipients to copy the
279
+ Corresponding Source along with the object code. If the place to
280
+ copy the object code is a network server, the Corresponding Source
281
+ may be on a different server (operated by you or a third party)
282
+ that supports equivalent copying facilities, provided you maintain
283
+ clear directions next to the object code saying where to find the
284
+ Corresponding Source. Regardless of what server hosts the
285
+ Corresponding Source, you remain obligated to ensure that it is
286
+ available for as long as needed to satisfy these requirements.
287
+
288
+ e) Convey the object code using peer-to-peer transmission, provided
289
+ you inform other peers where the object code and Corresponding
290
+ Source of the work are being offered to the general public at no
291
+ charge under subsection 6d.
292
+
293
+ A separable portion of the object code, whose source code is excluded
294
+ from the Corresponding Source as a System Library, need not be
295
+ included in conveying the object code work.
296
+
297
+ A "User Product" is either (1) a "consumer product", which means any
298
+ tangible personal property which is normally used for personal, family,
299
+ or household purposes, or (2) anything designed or sold for incorporation
300
+ into a dwelling. In determining whether a product is a consumer product,
301
+ doubtful cases shall be resolved in favor of coverage. For a particular
302
+ product received by a particular user, "normally used" refers to a
303
+ typical or common use of that class of product, regardless of the status
304
+ of the particular user or of the way in which the particular user
305
+ actually uses, or expects or is expected to use, the product. A product
306
+ is a consumer product regardless of whether the product has substantial
307
+ commercial, industrial or non-consumer uses, unless such uses represent
308
+ the only significant mode of use of the product.
309
+
310
+ "Installation Information" for a User Product means any methods,
311
+ procedures, authorization keys, or other information required to install
312
+ and execute modified versions of a covered work in that User Product from
313
+ a modified version of its Corresponding Source. The information must
314
+ suffice to ensure that the continued functioning of the modified object
315
+ code is in no case prevented or interfered with solely because
316
+ modification has been made.
317
+
318
+ If you convey an object code work under this section in, or with, or
319
+ specifically for use in, a User Product, and the conveying occurs as
320
+ part of a transaction in which the right of possession and use of the
321
+ User Product is transferred to the recipient in perpetuity or for a
322
+ fixed term (regardless of how the transaction is characterized), the
323
+ Corresponding Source conveyed under this section must be accompanied
324
+ by the Installation Information. But this requirement does not apply
325
+ if neither you nor any third party retains the ability to install
326
+ modified object code on the User Product (for example, the work has
327
+ been installed in ROM).
328
+
329
+ The requirement to provide Installation Information does not include a
330
+ requirement to continue to provide support service, warranty, or updates
331
+ for a work that has been modified or installed by the recipient, or for
332
+ the User Product in which it has been modified or installed. Access to a
333
+ network may be denied when the modification itself materially and
334
+ adversely affects the operation of the network or violates the rules and
335
+ protocols for communication across the network.
336
+
337
+ Corresponding Source conveyed, and Installation Information provided,
338
+ in accord with this section must be in a format that is publicly
339
+ documented (and with an implementation available to the public in
340
+ source code form), and must require no special password or key for
341
+ unpacking, reading or copying.
342
+
343
+ 7. Additional Terms.
344
+
345
+ "Additional permissions" are terms that supplement the terms of this
346
+ License by making exceptions from one or more of its conditions.
347
+ Additional permissions that are applicable to the entire Program shall
348
+ be treated as though they were included in this License, to the extent
349
+ that they are valid under applicable law. If additional permissions
350
+ apply only to part of the Program, that part may be used separately
351
+ under those permissions, but the entire Program remains governed by
352
+ this License without regard to the additional permissions.
353
+
354
+ When you convey a copy of a covered work, you may at your option
355
+ remove any additional permissions from that copy, or from any part of
356
+ it. (Additional permissions may be written to require their own
357
+ removal in certain cases when you modify the work.) You may place
358
+ additional permissions on material, added by you to a covered work,
359
+ for which you have or can give appropriate copyright permission.
360
+
361
+ Notwithstanding any other provision of this License, for material you
362
+ add to a covered work, you may (if authorized by the copyright holders of
363
+ that material) supplement the terms of this License with terms:
364
+
365
+ a) Disclaiming warranty or limiting liability differently from the
366
+ terms of sections 15 and 16 of this License; or
367
+
368
+ b) Requiring preservation of specified reasonable legal notices or
369
+ author attributions in that material or in the Appropriate Legal
370
+ Notices displayed by works containing it; or
371
+
372
+ c) Prohibiting misrepresentation of the origin of that material, or
373
+ requiring that modified versions of such material be marked in
374
+ reasonable ways as different from the original version; or
375
+
376
+ d) Limiting the use for publicity purposes of names of licensors or
377
+ authors of the material; or
378
+
379
+ e) Declining to grant rights under trademark law for use of some
380
+ trade names, trademarks, or service marks; or
381
+
382
+ f) Requiring indemnification of licensors and authors of that
383
+ material by anyone who conveys the material (or modified versions of
384
+ it) with contractual assumptions of liability to the recipient, for
385
+ any liability that these contractual assumptions directly impose on
386
+ those licensors and authors.
387
+
388
+ All other non-permissive additional terms are considered "further
389
+ restrictions" within the meaning of section 10. If the Program as you
390
+ received it, or any part of it, contains a notice stating that it is
391
+ governed by this License along with a term that is a further
392
+ restriction, you may remove that term. If a license document contains
393
+ a further restriction but permits relicensing or conveying under this
394
+ License, you may add to a covered work material governed by the terms
395
+ of that license document, provided that the further restriction does
396
+ not survive such relicensing or conveying.
397
+
398
+ If you add terms to a covered work in accord with this section, you
399
+ must place, in the relevant source files, a statement of the
400
+ additional terms that apply to those files, or a notice indicating
401
+ where to find the applicable terms.
402
+
403
+ Additional terms, permissive or non-permissive, may be stated in the
404
+ form of a separately written license, or stated as exceptions;
405
+ the above requirements apply either way.
406
+
407
+ 8. Termination.
408
+
409
+ You may not propagate or modify a covered work except as expressly
410
+ provided under this License. Any attempt otherwise to propagate or
411
+ modify it is void, and will automatically terminate your rights under
412
+ this License (including any patent licenses granted under the third
413
+ paragraph of section 11).
414
+
415
+ However, if you cease all violation of this License, then your
416
+ license from a particular copyright holder is reinstated (a)
417
+ provisionally, unless and until the copyright holder explicitly and
418
+ finally terminates your license, and (b) permanently, if the copyright
419
+ holder fails to notify you of the violation by some reasonable means
420
+ prior to 60 days after the cessation.
421
+
422
+ Moreover, your license from a particular copyright holder is
423
+ reinstated permanently if the copyright holder notifies you of the
424
+ violation by some reasonable means, this is the first time you have
425
+ received notice of violation of this License (for any work) from that
426
+ copyright holder, and you cure the violation prior to 30 days after
427
+ your receipt of the notice.
428
+
429
+ Termination of your rights under this section does not terminate the
430
+ licenses of parties who have received copies or rights from you under
431
+ this License. If your rights have been terminated and not permanently
432
+ reinstated, you do not qualify to receive new licenses for the same
433
+ material under section 10.
434
+
435
+ 9. Acceptance Not Required for Having Copies.
436
+
437
+ You are not required to accept this License in order to receive or
438
+ run a copy of the Program. Ancillary propagation of a covered work
439
+ occurring solely as a consequence of using peer-to-peer transmission
440
+ to receive a copy likewise does not require acceptance. However,
441
+ nothing other than this License grants you permission to propagate or
442
+ modify any covered work. These actions infringe copyright if you do
443
+ not accept this License. Therefore, by modifying or propagating a
444
+ covered work, you indicate your acceptance of this License to do so.
445
+
446
+ 10. Automatic Licensing of Downstream Recipients.
447
+
448
+ Each time you convey a covered work, the recipient automatically
449
+ receives a license from the original licensors, to run, modify and
450
+ propagate that work, subject to this License. You are not responsible
451
+ for enforcing compliance by third parties with this License.
452
+
453
+ An "entity transaction" is a transaction transferring control of an
454
+ organization, or substantially all assets of one, or subdividing an
455
+ organization, or merging organizations. If propagation of a covered
456
+ work results from an entity transaction, each party to that
457
+ transaction who receives a copy of the work also receives whatever
458
+ licenses to the work the party's predecessor in interest had or could
459
+ give under the previous paragraph, plus a right to possession of the
460
+ Corresponding Source of the work from the predecessor in interest, if
461
+ the predecessor has it or can get it with reasonable efforts.
462
+
463
+ You may not impose any further restrictions on the exercise of the
464
+ rights granted or affirmed under this License. For example, you may
465
+ not impose a license fee, royalty, or other charge for exercise of
466
+ rights granted under this License, and you may not initiate litigation
467
+ (including a cross-claim or counterclaim in a lawsuit) alleging that
468
+ any patent claim is infringed by making, using, selling, offering for
469
+ sale, or importing the Program or any portion of it.
470
+
471
+ 11. Patents.
472
+
473
+ A "contributor" is a copyright holder who authorizes use under this
474
+ License of the Program or a work on which the Program is based. The
475
+ work thus licensed is called the contributor's "contributor version".
476
+
477
+ A contributor's "essential patent claims" are all patent claims
478
+ owned or controlled by the contributor, whether already acquired or
479
+ hereafter acquired, that would be infringed by some manner, permitted
480
+ by this License, of making, using, or selling its contributor version,
481
+ but do not include claims that would be infringed only as a
482
+ consequence of further modification of the contributor version. For
483
+ purposes of this definition, "control" includes the right to grant
484
+ patent sublicenses in a manner consistent with the requirements of
485
+ this License.
486
+
487
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
488
+ patent license under the contributor's essential patent claims, to
489
+ make, use, sell, offer for sale, import and otherwise run, modify and
490
+ propagate the contents of its contributor version.
491
+
492
+ In the following three paragraphs, a "patent license" is any express
493
+ agreement or commitment, however denominated, not to enforce a patent
494
+ (such as an express permission to practice a patent or covenant not to
495
+ sue for patent infringement). To "grant" such a patent license to a
496
+ party means to make such an agreement or commitment not to enforce a
497
+ patent against the party.
498
+
499
+ If you convey a covered work, knowingly relying on a patent license,
500
+ and the Corresponding Source of the work is not available for anyone
501
+ to copy, free of charge and under the terms of this License, through a
502
+ publicly available network server or other readily accessible means,
503
+ then you must either (1) cause the Corresponding Source to be so
504
+ available, or (2) arrange to deprive yourself of the benefit of the
505
+ patent license for this particular work, or (3) arrange, in a manner
506
+ consistent with the requirements of this License, to extend the patent
507
+ license to downstream recipients. "Knowingly relying" means you have
508
+ actual knowledge that, but for the patent license, your conveying the
509
+ covered work in a country, or your recipient's use of the covered work
510
+ in a country, would infringe one or more identifiable patents in that
511
+ country that you have reason to believe are valid.
512
+
513
+ If, pursuant to or in connection with a single transaction or
514
+ arrangement, you convey, or propagate by procuring conveyance of, a
515
+ covered work, and grant a patent license to some of the parties
516
+ receiving the covered work authorizing them to use, propagate, modify
517
+ or convey a specific copy of the covered work, then the patent license
518
+ you grant is automatically extended to all recipients of the covered
519
+ work and works based on it.
520
+
521
+ A patent license is "discriminatory" if it does not include within
522
+ the scope of its coverage, prohibits the exercise of, or is
523
+ conditioned on the non-exercise of one or more of the rights that are
524
+ specifically granted under this License. You may not convey a covered
525
+ work if you are a party to an arrangement with a third party that is
526
+ in the business of distributing software, under which you make payment
527
+ to the third party based on the extent of your activity of conveying
528
+ the work, and under which the third party grants, to any of the
529
+ parties who would receive the covered work from you, a discriminatory
530
+ patent license (a) in connection with copies of the covered work
531
+ conveyed by you (or copies made from those copies), or (b) primarily
532
+ for and in connection with specific products or compilations that
533
+ contain the covered work, unless you entered into that arrangement,
534
+ or that patent license was granted, prior to 28 March 2007.
535
+
536
+ Nothing in this License shall be construed as excluding or limiting
537
+ any implied license or other defenses to infringement that may
538
+ otherwise be available to you under applicable patent law.
539
+
540
+ 12. No Surrender of Others' Freedom.
541
+
542
+ If conditions are imposed on you (whether by court order, agreement or
543
+ otherwise) that contradict the conditions of this License, they do not
544
+ excuse you from the conditions of this License. If you cannot convey a
545
+ covered work so as to satisfy simultaneously your obligations under this
546
+ License and any other pertinent obligations, then as a consequence you may
547
+ not convey it at all. For example, if you agree to terms that obligate you
548
+ to collect a royalty for further conveying from those to whom you convey
549
+ the Program, the only way you could satisfy both those terms and this
550
+ License would be to refrain entirely from conveying the Program.
551
+
552
+ 13. Use with the GNU Affero General Public License.
553
+
554
+ Notwithstanding any other provision of this License, you have
555
+ permission to link or combine any covered work with a work licensed
556
+ under version 3 of the GNU Affero General Public License into a single
557
+ combined work, and to convey the resulting work. The terms of this
558
+ License will continue to apply to the part which is the covered work,
559
+ but the special requirements of the GNU Affero General Public License,
560
+ section 13, concerning interaction through a network will apply to the
561
+ combination as such.
562
+
563
+ 14. Revised Versions of this License.
564
+
565
+ The Free Software Foundation may publish revised and/or new versions of
566
+ the GNU General Public License from time to time. Such new versions will
567
+ be similar in spirit to the present version, but may differ in detail to
568
+ address new problems or concerns.
569
+
570
+ Each version is given a distinguishing version number. If the
571
+ Program specifies that a certain numbered version of the GNU General
572
+ Public License "or any later version" applies to it, you have the
573
+ option of following the terms and conditions either of that numbered
574
+ version or of any later version published by the Free Software
575
+ Foundation. If the Program does not specify a version number of the
576
+ GNU General Public License, you may choose any version ever published
577
+ by the Free Software Foundation.
578
+
579
+ If the Program specifies that a proxy can decide which future
580
+ versions of the GNU General Public License can be used, that proxy's
581
+ public statement of acceptance of a version permanently authorizes you
582
+ to choose that version for the Program.
583
+
584
+ Later license versions may give you additional or different
585
+ permissions. However, no additional obligations are imposed on any
586
+ author or copyright holder as a result of your choosing to follow a
587
+ later version.
588
+
589
+ 15. Disclaimer of Warranty.
590
+
591
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592
+ APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593
+ HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594
+ OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595
+ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596
+ PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597
+ IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598
+ ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599
+
600
+ 16. Limitation of Liability.
601
+
602
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603
+ WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604
+ THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605
+ GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606
+ USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607
+ DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608
+ PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609
+ EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610
+ SUCH DAMAGES.
611
+
612
+ 17. Interpretation of Sections 15 and 16.
613
+
614
+ If the disclaimer of warranty and limitation of liability provided
615
+ above cannot be given local legal effect according to their terms,
616
+ reviewing courts shall apply local law that most closely approximates
617
+ an absolute waiver of all civil liability in connection with the
618
+ Program, unless a warranty or assumption of liability accompanies a
619
+ copy of the Program in return for a fee.
620
+
621
+ END OF TERMS AND CONDITIONS
622
+
623
+ How to Apply These Terms to Your New Programs
624
+
625
+ If you develop a new program, and you want it to be of the greatest
626
+ possible use to the public, the best way to achieve this is to make it
627
+ free software which everyone can redistribute and change under these terms.
628
+
629
+ To do so, attach the following notices to the program. It is safest
630
+ to attach them to the start of each source file to most effectively
631
+ state the exclusion of warranty; and each file should have at least
632
+ the "copyright" line and a pointer to where the full notice is found.
633
+
634
+ <one line to give the program's name and a brief idea of what it does.>
635
+ Copyright (C) <year> <name of author>
636
+
637
+ This program is free software: you can redistribute it and/or modify
638
+ it under the terms of the GNU General Public License as published by
639
+ the Free Software Foundation, either version 3 of the License, or
640
+ (at your option) any later version.
641
+
642
+ This program is distributed in the hope that it will be useful,
643
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
644
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645
+ GNU General Public License for more details.
646
+
647
+ You should have received a copy of the GNU General Public License
648
+ along with this program. If not, see <https://www.gnu.org/licenses/>.
649
+
650
+ Also add information on how to contact you by electronic and paper mail.
651
+
652
+ If the program does terminal interaction, make it output a short
653
+ notice like this when it starts in an interactive mode:
654
+
655
+ <program> Copyright (C) <year> <name of author>
656
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657
+ This is free software, and you are welcome to redistribute it
658
+ under certain conditions; type `show c' for details.
659
+
660
+ The hypothetical commands `show w' and `show c' should show the appropriate
661
+ parts of the General Public License. Of course, your program's commands
662
+ might be different; for a GUI interface, you would use an "about box".
663
+
664
+ You should also get your employer (if you work as a programmer) or school,
665
+ if any, to sign a "copyright disclaimer" for the program, if necessary.
666
+ For more information on this, and how to apply and follow the GNU GPL, see
667
+ <https://www.gnu.org/licenses/>.
668
+
669
+ The GNU General Public License does not permit incorporating your program
670
+ into proprietary programs. If your program is a subroutine library, you
671
+ may consider it more useful to permit linking proprietary applications with
672
+ the library. If this is what you want to do, use the GNU Lesser General
673
+ Public License instead of this License. But first, please read
674
+ <https://www.gnu.org/licenses/why-not-lgpl.html>.
modules_forge/packages/comfy/lora.py ADDED
@@ -0,0 +1,232 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # https://github.com/comfyanonymous/ComfyUI/blob/v0.3.77/comfy/lora.py
2
+
3
+ """
4
+ This file is part of ComfyUI.
5
+ Copyright (C) 2024 Comfy
6
+
7
+ This program is free software: you can redistribute it and/or modify
8
+ it under the terms of the GNU General Public License as published by
9
+ the Free Software Foundation, either version 3 of the License, or
10
+ (at your option) any later version.
11
+
12
+ This program is distributed in the hope that it will be useful,
13
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
14
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15
+ GNU General Public License for more details.
16
+
17
+ You should have received a copy of the GNU General Public License
18
+ along with this program. If not, see <https://www.gnu.org/licenses/>.
19
+ """
20
+
21
+ import torch
22
+
23
+ from modules_forge.packages.comfy import weight_adapter
24
+
25
+ from .utils import flux_to_diffusers, unet_to_diffusers, z_image_to_diffusers
26
+
27
+ LORA_CLIP_MAP = {
28
+ "mlp.fc1": "mlp_fc1",
29
+ "mlp.fc2": "mlp_fc2",
30
+ "self_attn.k_proj": "self_attn_k_proj",
31
+ "self_attn.q_proj": "self_attn_q_proj",
32
+ "self_attn.v_proj": "self_attn_v_proj",
33
+ "self_attn.out_proj": "self_attn_out_proj",
34
+ }
35
+
36
+
37
+ def load_lora(lora, to_load):
38
+
39
+ def convert_lora_bfl_control(sd): # BFL loras for Flux
40
+ sd_out = {}
41
+ for k in sd:
42
+ k_to = "diffusion_model.{}".format(k.replace(".lora_B.bias", ".diff_b").replace("_norm.scale", "_norm.scale.set_weight"))
43
+ sd_out[k_to] = sd[k]
44
+
45
+ sd_out["diffusion_model.img_in.reshape_weight"] = torch.tensor([sd["img_in.lora_B.weight"].shape[0], sd["img_in.lora_A.weight"].shape[1]])
46
+ return sd_out
47
+
48
+ if "img_in.lora_A.weight" in lora and "single_blocks.0.norm.key_norm.scale" in lora:
49
+ lora = convert_lora_bfl_control(lora)
50
+
51
+ patch_dict = {}
52
+ loaded_keys = set()
53
+ for x in to_load:
54
+ alpha_name = "{}.alpha".format(x)
55
+ alpha = None
56
+ if alpha_name in lora.keys():
57
+ alpha = lora[alpha_name].item()
58
+ loaded_keys.add(alpha_name)
59
+
60
+ dora_scale_name = "{}.dora_scale".format(x)
61
+ dora_scale = None
62
+ if dora_scale_name in lora.keys():
63
+ dora_scale = lora[dora_scale_name]
64
+ loaded_keys.add(dora_scale_name)
65
+
66
+ for adapter_cls in weight_adapter.adapters:
67
+ adapter = adapter_cls.load(x, lora, alpha, dora_scale, loaded_keys)
68
+ if adapter is not None:
69
+ patch_dict[to_load[x]] = adapter
70
+ loaded_keys.update(adapter.loaded_keys)
71
+ continue
72
+
73
+ w_norm_name = "{}.w_norm".format(x)
74
+ b_norm_name = "{}.b_norm".format(x)
75
+ w_norm = lora.get(w_norm_name, None)
76
+ b_norm = lora.get(b_norm_name, None)
77
+
78
+ if w_norm is not None:
79
+ loaded_keys.add(w_norm_name)
80
+ patch_dict[to_load[x]] = ("diff", (w_norm,))
81
+ if b_norm is not None:
82
+ loaded_keys.add(b_norm_name)
83
+ patch_dict["{}.bias".format(to_load[x][: -len(".weight")])] = ("diff", (b_norm,))
84
+
85
+ diff_name = "{}.diff".format(x)
86
+ diff_weight = lora.get(diff_name, None)
87
+ if diff_weight is not None:
88
+ patch_dict[to_load[x]] = ("diff", (diff_weight,))
89
+ loaded_keys.add(diff_name)
90
+
91
+ diff_bias_name = "{}.diff_b".format(x)
92
+ diff_bias = lora.get(diff_bias_name, None)
93
+ if diff_bias is not None:
94
+ patch_dict["{}.bias".format(to_load[x][: -len(".weight")])] = ("diff", (diff_bias,))
95
+ loaded_keys.add(diff_bias_name)
96
+
97
+ set_weight_name = "{}.set_weight".format(x)
98
+ set_weight = lora.get(set_weight_name, None)
99
+ if set_weight is not None:
100
+ patch_dict[to_load[x]] = ("set", (set_weight,))
101
+ loaded_keys.add(set_weight_name)
102
+
103
+ remaining_dict = {x: y for x, y in lora.items() if x not in loaded_keys}
104
+ return patch_dict, remaining_dict
105
+
106
+
107
+ def model_lora_keys_clip(model, key_map={}):
108
+ sdk = model.state_dict().keys()
109
+ for k in sdk:
110
+ if k.endswith(".weight"):
111
+ key_map["text_encoders.{}".format(k[: -len(".weight")])] = k # generic lora format without any weird key names
112
+
113
+ text_model_lora_key = "lora_te_text_model_encoder_layers_{}_{}"
114
+ clip_l_present = False
115
+ clip_g_present = False
116
+ for b in range(32): # TODO: clean up
117
+ for c in LORA_CLIP_MAP:
118
+ k = "clip_h.transformer.text_model.encoder.layers.{}.{}.weight".format(b, c)
119
+ if k in sdk:
120
+ lora_key = text_model_lora_key.format(b, LORA_CLIP_MAP[c])
121
+ key_map[lora_key] = k
122
+ lora_key = "lora_te1_text_model_encoder_layers_{}_{}".format(b, LORA_CLIP_MAP[c])
123
+ key_map[lora_key] = k
124
+ lora_key = "text_encoder.text_model.encoder.layers.{}.{}".format(b, c) # diffusers lora
125
+ key_map[lora_key] = k
126
+
127
+ k = "clip_l.transformer.text_model.encoder.layers.{}.{}.weight".format(b, c)
128
+ if k in sdk:
129
+ lora_key = text_model_lora_key.format(b, LORA_CLIP_MAP[c])
130
+ key_map[lora_key] = k
131
+ lora_key = "lora_te1_text_model_encoder_layers_{}_{}".format(b, LORA_CLIP_MAP[c]) # SDXL base
132
+ key_map[lora_key] = k
133
+ clip_l_present = True
134
+ lora_key = "text_encoder.text_model.encoder.layers.{}.{}".format(b, c) # diffusers lora
135
+ key_map[lora_key] = k
136
+
137
+ k = "clip_g.transformer.text_model.encoder.layers.{}.{}.weight".format(b, c)
138
+ if k in sdk:
139
+ clip_g_present = True
140
+ if clip_l_present:
141
+ lora_key = "lora_te2_text_model_encoder_layers_{}_{}".format(b, LORA_CLIP_MAP[c]) # SDXL base
142
+ key_map[lora_key] = k
143
+ lora_key = "text_encoder_2.text_model.encoder.layers.{}.{}".format(b, c) # diffusers lora
144
+ key_map[lora_key] = k
145
+ else:
146
+ lora_key = "lora_te_text_model_encoder_layers_{}_{}".format(b, LORA_CLIP_MAP[c]) # TODO: test if this is correct for SDXL-Refiner
147
+ key_map[lora_key] = k
148
+ lora_key = "text_encoder.text_model.encoder.layers.{}.{}".format(b, c) # diffusers lora
149
+ key_map[lora_key] = k
150
+ lora_key = "lora_prior_te_text_model_encoder_layers_{}_{}".format(b, LORA_CLIP_MAP[c]) # cascade lora: TODO put lora key prefix in the model config
151
+ key_map[lora_key] = k
152
+
153
+ for k in sdk:
154
+ if k.endswith(".weight") and k.startswith("t5xxl.transformer."): # OneTrainer SD3 and Flux lora
155
+ l_key = k[len("t5xxl.transformer.") : -len(".weight")]
156
+ t5_index = 1
157
+ if clip_g_present:
158
+ t5_index += 1
159
+ if clip_l_present:
160
+ t5_index += 1
161
+ if t5_index == 2:
162
+ key_map["lora_te{}_{}".format(t5_index, l_key.replace(".", "_"))] = k # OneTrainer Flux
163
+ t5_index += 1
164
+
165
+ key_map["lora_te{}_{}".format(t5_index, l_key.replace(".", "_"))] = k
166
+
167
+ return key_map
168
+
169
+
170
+ def model_lora_keys_unet(model, key_map={}):
171
+ sd = model.state_dict()
172
+ sdk = sd.keys()
173
+
174
+ for k in sdk:
175
+ if k.startswith("diffusion_model."):
176
+ if k.endswith(".weight"):
177
+ key_lora = k[len("diffusion_model.") : -len(".weight")].replace(".", "_")
178
+ key_map["lora_unet_{}".format(key_lora)] = k
179
+ key_map["{}".format(k[: -len(".weight")])] = k # generic lora format without any weird key names
180
+ else:
181
+ key_map["{}".format(k)] = k # generic lora format for not .weight without any weird key names
182
+
183
+ diffusers_keys = unet_to_diffusers(model.diffusion_model.config)
184
+ for k in diffusers_keys:
185
+ if k.endswith(".weight"):
186
+ unet_key = "diffusion_model.{}".format(diffusers_keys[k])
187
+ key_lora = k[: -len(".weight")].replace(".", "_")
188
+ key_map["lora_unet_{}".format(key_lora)] = unet_key
189
+ key_map["lycoris_{}".format(key_lora)] = unet_key # simpletuner lycoris format
190
+
191
+ diffusers_lora_prefix = ["", "unet."]
192
+ for p in diffusers_lora_prefix:
193
+ diffusers_lora_key = "{}{}".format(p, k[: -len(".weight")].replace(".to_", ".processor.to_"))
194
+ if diffusers_lora_key.endswith(".to_out.0"):
195
+ diffusers_lora_key = diffusers_lora_key[:-2]
196
+ key_map[diffusers_lora_key] = unet_key
197
+
198
+ _model_name: str = model.config.huggingface_repo.lower()
199
+
200
+ if "flux" in _model_name or "chroma" in _model_name: # Diffusers lora Flux
201
+ diffusers_keys = flux_to_diffusers(model.diffusion_model.config, output_prefix="diffusion_model.")
202
+ for k in diffusers_keys:
203
+ if k.endswith(".weight"):
204
+ to = diffusers_keys[k]
205
+ key_map["transformer.{}".format(k[: -len(".weight")])] = to # simpletrainer and probably regular diffusers flux lora format
206
+ key_map["lycoris_{}".format(k[: -len(".weight")].replace(".", "_"))] = to # simpletrainer lycoris
207
+ key_map["lora_transformer_{}".format(k[: -len(".weight")].replace(".", "_"))] = to # onetrainer
208
+ for k in sdk:
209
+ hidden_size = model.diffusion_model.config.get("hidden_size", 0)
210
+ if k.endswith(".weight") and ".linear1." in k:
211
+ key_map["{}".format(k.replace(".linear1.weight", ".linear1_qkv"))] = (k, (0, 0, hidden_size * 3))
212
+
213
+ if "qwen" in _model_name:
214
+ for k in sdk:
215
+ if k.startswith("diffusion_model.") and k.endswith(".weight"): # QwenImage lora format
216
+ key_lora = k[len("diffusion_model.") : -len(".weight")]
217
+ # Direct mapping for transformer_blocks format (QwenImage LoRA format)
218
+ key_map["{}".format(key_lora)] = k
219
+ # Support transformer prefix format
220
+ key_map["transformer.{}".format(key_lora)] = k
221
+ key_map["lycoris_{}".format(key_lora.replace(".", "_"))] = k # SimpleTuner lycoris format
222
+
223
+ if "lumina" in _model_name or "z-image" in _model_name:
224
+ diffusers_keys = z_image_to_diffusers(model.diffusion_model.config, output_prefix="diffusion_model.")
225
+ for k in diffusers_keys:
226
+ if k.endswith(".weight"):
227
+ to = diffusers_keys[k]
228
+ key_lora = k[: -len(".weight")]
229
+ key_map["diffusion_model.{}".format(key_lora)] = to
230
+ key_map["lycoris_{}".format(key_lora.replace(".", "_"))] = to
231
+
232
+ return key_map
modules_forge/packages/comfy/utils.py ADDED
@@ -0,0 +1,336 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # https://github.com/comfyanonymous/ComfyUI/blob/v0.3.77/comfy/utils.py
2
+
3
+ """
4
+ This file is part of ComfyUI.
5
+ Copyright (C) 2024 Comfy
6
+
7
+ This program is free software: you can redistribute it and/or modify
8
+ it under the terms of the GNU General Public License as published by
9
+ the Free Software Foundation, either version 3 of the License, or
10
+ (at your option) any later version.
11
+
12
+ This program is distributed in the hope that it will be useful,
13
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
14
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15
+ GNU General Public License for more details.
16
+
17
+ You should have received a copy of the GNU General Public License
18
+ along with this program. If not, see <https://www.gnu.org/licenses/>.
19
+ """
20
+
21
+ import torch
22
+
23
+ UNET_MAP_ATTENTIONS = {
24
+ "proj_in.weight",
25
+ "proj_in.bias",
26
+ "proj_out.weight",
27
+ "proj_out.bias",
28
+ "norm.weight",
29
+ "norm.bias",
30
+ }
31
+
32
+ TRANSFORMER_BLOCKS = {
33
+ "norm1.weight",
34
+ "norm1.bias",
35
+ "norm2.weight",
36
+ "norm2.bias",
37
+ "norm3.weight",
38
+ "norm3.bias",
39
+ "attn1.to_q.weight",
40
+ "attn1.to_k.weight",
41
+ "attn1.to_v.weight",
42
+ "attn1.to_out.0.weight",
43
+ "attn1.to_out.0.bias",
44
+ "attn2.to_q.weight",
45
+ "attn2.to_k.weight",
46
+ "attn2.to_v.weight",
47
+ "attn2.to_out.0.weight",
48
+ "attn2.to_out.0.bias",
49
+ "ff.net.0.proj.weight",
50
+ "ff.net.0.proj.bias",
51
+ "ff.net.2.weight",
52
+ "ff.net.2.bias",
53
+ }
54
+
55
+ UNET_MAP_RESNET = {
56
+ "in_layers.2.weight": "conv1.weight",
57
+ "in_layers.2.bias": "conv1.bias",
58
+ "emb_layers.1.weight": "time_emb_proj.weight",
59
+ "emb_layers.1.bias": "time_emb_proj.bias",
60
+ "out_layers.3.weight": "conv2.weight",
61
+ "out_layers.3.bias": "conv2.bias",
62
+ "skip_connection.weight": "conv_shortcut.weight",
63
+ "skip_connection.bias": "conv_shortcut.bias",
64
+ "in_layers.0.weight": "norm1.weight",
65
+ "in_layers.0.bias": "norm1.bias",
66
+ "out_layers.0.weight": "norm2.weight",
67
+ "out_layers.0.bias": "norm2.bias",
68
+ }
69
+
70
+ UNET_MAP_BASIC = {
71
+ ("label_emb.0.0.weight", "class_embedding.linear_1.weight"),
72
+ ("label_emb.0.0.bias", "class_embedding.linear_1.bias"),
73
+ ("label_emb.0.2.weight", "class_embedding.linear_2.weight"),
74
+ ("label_emb.0.2.bias", "class_embedding.linear_2.bias"),
75
+ ("label_emb.0.0.weight", "add_embedding.linear_1.weight"),
76
+ ("label_emb.0.0.bias", "add_embedding.linear_1.bias"),
77
+ ("label_emb.0.2.weight", "add_embedding.linear_2.weight"),
78
+ ("label_emb.0.2.bias", "add_embedding.linear_2.bias"),
79
+ ("input_blocks.0.0.weight", "conv_in.weight"),
80
+ ("input_blocks.0.0.bias", "conv_in.bias"),
81
+ ("out.0.weight", "conv_norm_out.weight"),
82
+ ("out.0.bias", "conv_norm_out.bias"),
83
+ ("out.2.weight", "conv_out.weight"),
84
+ ("out.2.bias", "conv_out.bias"),
85
+ ("time_embed.0.weight", "time_embedding.linear_1.weight"),
86
+ ("time_embed.0.bias", "time_embedding.linear_1.bias"),
87
+ ("time_embed.2.weight", "time_embedding.linear_2.weight"),
88
+ ("time_embed.2.bias", "time_embedding.linear_2.bias"),
89
+ }
90
+
91
+
92
+ def unet_to_diffusers(unet_config):
93
+ if "num_res_blocks" not in unet_config:
94
+ return {}
95
+ num_res_blocks = unet_config["num_res_blocks"]
96
+ channel_mult = unet_config["channel_mult"]
97
+ transformer_depth = unet_config["transformer_depth"][:]
98
+ transformer_depth_output = unet_config["transformer_depth_output"][:]
99
+ num_blocks = len(channel_mult)
100
+
101
+ transformers_mid = unet_config.get("transformer_depth_middle", None)
102
+
103
+ diffusers_unet_map = {}
104
+ for x in range(num_blocks):
105
+ n = 1 + (num_res_blocks[x] + 1) * x
106
+ for i in range(num_res_blocks[x]):
107
+ for b in UNET_MAP_RESNET:
108
+ diffusers_unet_map["down_blocks.{}.resnets.{}.{}".format(x, i, UNET_MAP_RESNET[b])] = "input_blocks.{}.0.{}".format(n, b)
109
+ num_transformers = transformer_depth.pop(0)
110
+ if num_transformers > 0:
111
+ for b in UNET_MAP_ATTENTIONS:
112
+ diffusers_unet_map["down_blocks.{}.attentions.{}.{}".format(x, i, b)] = "input_blocks.{}.1.{}".format(n, b)
113
+ for t in range(num_transformers):
114
+ for b in TRANSFORMER_BLOCKS:
115
+ diffusers_unet_map["down_blocks.{}.attentions.{}.transformer_blocks.{}.{}".format(x, i, t, b)] = "input_blocks.{}.1.transformer_blocks.{}.{}".format(n, t, b)
116
+ n += 1
117
+ for k in ["weight", "bias"]:
118
+ diffusers_unet_map["down_blocks.{}.downsamplers.0.conv.{}".format(x, k)] = "input_blocks.{}.0.op.{}".format(n, k)
119
+
120
+ i = 0
121
+ for b in UNET_MAP_ATTENTIONS:
122
+ diffusers_unet_map["mid_block.attentions.{}.{}".format(i, b)] = "middle_block.1.{}".format(b)
123
+ for t in range(transformers_mid):
124
+ for b in TRANSFORMER_BLOCKS:
125
+ diffusers_unet_map["mid_block.attentions.{}.transformer_blocks.{}.{}".format(i, t, b)] = "middle_block.1.transformer_blocks.{}.{}".format(t, b)
126
+
127
+ for i, n in enumerate([0, 2]):
128
+ for b in UNET_MAP_RESNET:
129
+ diffusers_unet_map["mid_block.resnets.{}.{}".format(i, UNET_MAP_RESNET[b])] = "middle_block.{}.{}".format(n, b)
130
+
131
+ num_res_blocks = list(reversed(num_res_blocks))
132
+ for x in range(num_blocks):
133
+ n = (num_res_blocks[x] + 1) * x
134
+ l = num_res_blocks[x] + 1
135
+ for i in range(l):
136
+ c = 0
137
+ for b in UNET_MAP_RESNET:
138
+ diffusers_unet_map["up_blocks.{}.resnets.{}.{}".format(x, i, UNET_MAP_RESNET[b])] = "output_blocks.{}.0.{}".format(n, b)
139
+ c += 1
140
+ num_transformers = transformer_depth_output.pop()
141
+ if num_transformers > 0:
142
+ c += 1
143
+ for b in UNET_MAP_ATTENTIONS:
144
+ diffusers_unet_map["up_blocks.{}.attentions.{}.{}".format(x, i, b)] = "output_blocks.{}.1.{}".format(n, b)
145
+ for t in range(num_transformers):
146
+ for b in TRANSFORMER_BLOCKS:
147
+ diffusers_unet_map["up_blocks.{}.attentions.{}.transformer_blocks.{}.{}".format(x, i, t, b)] = "output_blocks.{}.1.transformer_blocks.{}.{}".format(n, t, b)
148
+ if i == l - 1:
149
+ for k in ["weight", "bias"]:
150
+ diffusers_unet_map["up_blocks.{}.upsamplers.0.conv.{}".format(x, k)] = "output_blocks.{}.{}.conv.{}".format(n, c, k)
151
+ n += 1
152
+
153
+ for k in UNET_MAP_BASIC:
154
+ diffusers_unet_map[k[1]] = k[0]
155
+
156
+ return diffusers_unet_map
157
+
158
+
159
+ def swap_scale_shift(weight):
160
+ shift, scale = weight.chunk(2, dim=0)
161
+ new_weight = torch.cat([scale, shift], dim=0)
162
+ return new_weight
163
+
164
+
165
+ def flux_to_diffusers(mmdit_config, output_prefix=""):
166
+ n_double_layers = mmdit_config.get("depth", 0)
167
+ n_single_layers = mmdit_config.get("depth_single_blocks", 0)
168
+ hidden_size = mmdit_config.get("hidden_size", 0)
169
+
170
+ key_map = {}
171
+ for index in range(n_double_layers):
172
+ prefix_from = "transformer_blocks.{}".format(index)
173
+ prefix_to = "{}double_blocks.{}".format(output_prefix, index)
174
+
175
+ for end in ("weight", "bias"):
176
+ k = "{}.attn.".format(prefix_from)
177
+ qkv = "{}.img_attn.qkv.{}".format(prefix_to, end)
178
+ key_map["{}to_q.{}".format(k, end)] = (qkv, (0, 0, hidden_size))
179
+ key_map["{}to_k.{}".format(k, end)] = (qkv, (0, hidden_size, hidden_size))
180
+ key_map["{}to_v.{}".format(k, end)] = (qkv, (0, hidden_size * 2, hidden_size))
181
+
182
+ k = "{}.attn.".format(prefix_from)
183
+ qkv = "{}.txt_attn.qkv.{}".format(prefix_to, end)
184
+ key_map["{}add_q_proj.{}".format(k, end)] = (qkv, (0, 0, hidden_size))
185
+ key_map["{}add_k_proj.{}".format(k, end)] = (qkv, (0, hidden_size, hidden_size))
186
+ key_map["{}add_v_proj.{}".format(k, end)] = (qkv, (0, hidden_size * 2, hidden_size))
187
+
188
+ block_map = {
189
+ "attn.to_out.0.weight": "img_attn.proj.weight",
190
+ "attn.to_out.0.bias": "img_attn.proj.bias",
191
+ "norm1.linear.weight": "img_mod.lin.weight",
192
+ "norm1.linear.bias": "img_mod.lin.bias",
193
+ "norm1_context.linear.weight": "txt_mod.lin.weight",
194
+ "norm1_context.linear.bias": "txt_mod.lin.bias",
195
+ "attn.to_add_out.weight": "txt_attn.proj.weight",
196
+ "attn.to_add_out.bias": "txt_attn.proj.bias",
197
+ "ff.net.0.proj.weight": "img_mlp.0.weight",
198
+ "ff.net.0.proj.bias": "img_mlp.0.bias",
199
+ "ff.net.2.weight": "img_mlp.2.weight",
200
+ "ff.net.2.bias": "img_mlp.2.bias",
201
+ "ff_context.net.0.proj.weight": "txt_mlp.0.weight",
202
+ "ff_context.net.0.proj.bias": "txt_mlp.0.bias",
203
+ "ff_context.net.2.weight": "txt_mlp.2.weight",
204
+ "ff_context.net.2.bias": "txt_mlp.2.bias",
205
+ "attn.norm_q.weight": "img_attn.norm.query_norm.scale",
206
+ "attn.norm_k.weight": "img_attn.norm.key_norm.scale",
207
+ "attn.norm_added_q.weight": "txt_attn.norm.query_norm.scale",
208
+ "attn.norm_added_k.weight": "txt_attn.norm.key_norm.scale",
209
+ }
210
+
211
+ for k in block_map:
212
+ key_map["{}.{}".format(prefix_from, k)] = "{}.{}".format(prefix_to, block_map[k])
213
+
214
+ for index in range(n_single_layers):
215
+ prefix_from = "single_transformer_blocks.{}".format(index)
216
+ prefix_to = "{}single_blocks.{}".format(output_prefix, index)
217
+
218
+ for end in ("weight", "bias"):
219
+ k = "{}.attn.".format(prefix_from)
220
+ qkv = "{}.linear1.{}".format(prefix_to, end)
221
+ key_map["{}to_q.{}".format(k, end)] = (qkv, (0, 0, hidden_size))
222
+ key_map["{}to_k.{}".format(k, end)] = (qkv, (0, hidden_size, hidden_size))
223
+ key_map["{}to_v.{}".format(k, end)] = (qkv, (0, hidden_size * 2, hidden_size))
224
+ key_map["{}.proj_mlp.{}".format(prefix_from, end)] = (qkv, (0, hidden_size * 3, hidden_size * 4))
225
+
226
+ block_map = {
227
+ "norm.linear.weight": "modulation.lin.weight",
228
+ "norm.linear.bias": "modulation.lin.bias",
229
+ "proj_out.weight": "linear2.weight",
230
+ "proj_out.bias": "linear2.bias",
231
+ "attn.norm_q.weight": "norm.query_norm.scale",
232
+ "attn.norm_k.weight": "norm.key_norm.scale",
233
+ }
234
+
235
+ for k in block_map:
236
+ key_map["{}.{}".format(prefix_from, k)] = "{}.{}".format(prefix_to, block_map[k])
237
+
238
+ MAP_BASIC = {
239
+ ("final_layer.linear.bias", "proj_out.bias"),
240
+ ("final_layer.linear.weight", "proj_out.weight"),
241
+ ("img_in.bias", "x_embedder.bias"),
242
+ ("img_in.weight", "x_embedder.weight"),
243
+ ("time_in.in_layer.bias", "time_text_embed.timestep_embedder.linear_1.bias"),
244
+ ("time_in.in_layer.weight", "time_text_embed.timestep_embedder.linear_1.weight"),
245
+ ("time_in.out_layer.bias", "time_text_embed.timestep_embedder.linear_2.bias"),
246
+ ("time_in.out_layer.weight", "time_text_embed.timestep_embedder.linear_2.weight"),
247
+ ("txt_in.bias", "context_embedder.bias"),
248
+ ("txt_in.weight", "context_embedder.weight"),
249
+ ("vector_in.in_layer.bias", "time_text_embed.text_embedder.linear_1.bias"),
250
+ ("vector_in.in_layer.weight", "time_text_embed.text_embedder.linear_1.weight"),
251
+ ("vector_in.out_layer.bias", "time_text_embed.text_embedder.linear_2.bias"),
252
+ ("vector_in.out_layer.weight", "time_text_embed.text_embedder.linear_2.weight"),
253
+ ("guidance_in.in_layer.bias", "time_text_embed.guidance_embedder.linear_1.bias"),
254
+ ("guidance_in.in_layer.weight", "time_text_embed.guidance_embedder.linear_1.weight"),
255
+ ("guidance_in.out_layer.bias", "time_text_embed.guidance_embedder.linear_2.bias"),
256
+ ("guidance_in.out_layer.weight", "time_text_embed.guidance_embedder.linear_2.weight"),
257
+ ("final_layer.adaLN_modulation.1.bias", "norm_out.linear.bias", swap_scale_shift),
258
+ ("final_layer.adaLN_modulation.1.weight", "norm_out.linear.weight", swap_scale_shift),
259
+ ("pos_embed_input.bias", "controlnet_x_embedder.bias"),
260
+ ("pos_embed_input.weight", "controlnet_x_embedder.weight"),
261
+ }
262
+
263
+ for k in MAP_BASIC:
264
+ if len(k) > 2:
265
+ key_map[k[1]] = ("{}{}".format(output_prefix, k[0]), None, k[2])
266
+ else:
267
+ key_map[k[1]] = "{}{}".format(output_prefix, k[0])
268
+
269
+ return key_map
270
+
271
+
272
+ def z_image_to_diffusers(mmdit_config, output_prefix=""):
273
+ n_layers = mmdit_config.get("n_layers", 0)
274
+ hidden_size = mmdit_config.get("dim", 0)
275
+ n_context_refiner = mmdit_config.get("n_refiner_layers", 2)
276
+ n_noise_refiner = mmdit_config.get("n_refiner_layers", 2)
277
+ key_map = {}
278
+
279
+ def add_block_keys(prefix_from, prefix_to, has_adaln=True):
280
+ for end in ("weight", "bias"):
281
+ k = "{}.attention.".format(prefix_from)
282
+ qkv = "{}.attention.qkv.{}".format(prefix_to, end)
283
+ key_map["{}to_q.{}".format(k, end)] = (qkv, (0, 0, hidden_size))
284
+ key_map["{}to_k.{}".format(k, end)] = (qkv, (0, hidden_size, hidden_size))
285
+ key_map["{}to_v.{}".format(k, end)] = (qkv, (0, hidden_size * 2, hidden_size))
286
+
287
+ block_map = {
288
+ "attention.norm_q.weight": "attention.q_norm.weight",
289
+ "attention.norm_k.weight": "attention.k_norm.weight",
290
+ "attention.to_out.0.weight": "attention.out.weight",
291
+ "attention.to_out.0.bias": "attention.out.bias",
292
+ "attention_norm1.weight": "attention_norm1.weight",
293
+ "attention_norm2.weight": "attention_norm2.weight",
294
+ "feed_forward.w1.weight": "feed_forward.w1.weight",
295
+ "feed_forward.w2.weight": "feed_forward.w2.weight",
296
+ "feed_forward.w3.weight": "feed_forward.w3.weight",
297
+ "ffn_norm1.weight": "ffn_norm1.weight",
298
+ "ffn_norm2.weight": "ffn_norm2.weight",
299
+ }
300
+ if has_adaln:
301
+ block_map["adaLN_modulation.0.weight"] = "adaLN_modulation.0.weight"
302
+ block_map["adaLN_modulation.0.bias"] = "adaLN_modulation.0.bias"
303
+ for k, v in block_map.items():
304
+ key_map["{}.{}".format(prefix_from, k)] = "{}.{}".format(prefix_to, v)
305
+
306
+ for i in range(n_layers):
307
+ add_block_keys("layers.{}".format(i), "{}layers.{}".format(output_prefix, i))
308
+
309
+ for i in range(n_context_refiner):
310
+ add_block_keys("context_refiner.{}".format(i), "{}context_refiner.{}".format(output_prefix, i))
311
+
312
+ for i in range(n_noise_refiner):
313
+ add_block_keys("noise_refiner.{}".format(i), "{}noise_refiner.{}".format(output_prefix, i))
314
+
315
+ MAP_BASIC = [
316
+ ("final_layer.linear.weight", "all_final_layer.2-1.linear.weight"),
317
+ ("final_layer.linear.bias", "all_final_layer.2-1.linear.bias"),
318
+ ("final_layer.adaLN_modulation.1.weight", "all_final_layer.2-1.adaLN_modulation.1.weight"),
319
+ ("final_layer.adaLN_modulation.1.bias", "all_final_layer.2-1.adaLN_modulation.1.bias"),
320
+ ("x_embedder.weight", "all_x_embedder.2-1.weight"),
321
+ ("x_embedder.bias", "all_x_embedder.2-1.bias"),
322
+ ("x_pad_token", "x_pad_token"),
323
+ ("cap_embedder.0.weight", "cap_embedder.0.weight"),
324
+ ("cap_embedder.1.weight", "cap_embedder.1.weight"),
325
+ ("cap_embedder.1.bias", "cap_embedder.1.bias"),
326
+ ("cap_pad_token", "cap_pad_token"),
327
+ ("t_embedder.mlp.0.weight", "t_embedder.mlp.0.weight"),
328
+ ("t_embedder.mlp.0.bias", "t_embedder.mlp.0.bias"),
329
+ ("t_embedder.mlp.2.weight", "t_embedder.mlp.2.weight"),
330
+ ("t_embedder.mlp.2.bias", "t_embedder.mlp.2.bias"),
331
+ ]
332
+
333
+ for c, diffusers in MAP_BASIC:
334
+ key_map[diffusers] = "{}{}".format(output_prefix, c)
335
+
336
+ return key_map
modules_forge/packages/comfy/weight_adapter/__init__.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # https://github.com/comfyanonymous/ComfyUI/tree/v0.3.77/comfy/weight_adapter
2
+
3
+ from typing import Final
4
+
5
+ from .base import WeightAdapterBase
6
+ from .boft import BOFTAdapter
7
+ from .glora import GLoRAAdapter
8
+ from .loha import LoHaAdapter
9
+ from .lokr import LoKrAdapter
10
+ from .lora import LoRAAdapter
11
+ from .oft import OFTAdapter
12
+ from .oftv2 import OFTv2Adapter
13
+
14
+ adapters: Final[list[type[WeightAdapterBase]]] = [
15
+ BOFTAdapter,
16
+ GLoRAAdapter,
17
+ LoHaAdapter,
18
+ LoKrAdapter,
19
+ LoRAAdapter,
20
+ OFTAdapter,
21
+ OFTv2Adapter,
22
+ ]
23
+
24
+ adapter_maps: Final[dict[str, type[WeightAdapterBase]]] = {
25
+ "LoRA": LoRAAdapter,
26
+ "LoHa": LoHaAdapter,
27
+ "LoKr": LoKrAdapter,
28
+ "OFT": OFTAdapter,
29
+ "OFTv2": OFTv2Adapter,
30
+ # "GLoRA": GLoRAAdapter,
31
+ # "BOFT": BOFTAdapter,
32
+ }
33
+
34
+
35
+ __all__ = [
36
+ "WeightAdapterBase",
37
+ "adapters",
38
+ "adapter_maps",
39
+ ] + [a.__name__ for a in adapters]
modules_forge/packages/comfy/weight_adapter/base.py ADDED
@@ -0,0 +1,165 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Optional
2
+
3
+ import torch
4
+ import torch.nn as nn
5
+
6
+ from backend import memory_management
7
+
8
+
9
+ class WeightAdapterBase:
10
+ name: str
11
+ loaded_keys: set[str]
12
+ weights: list[torch.Tensor]
13
+
14
+ @classmethod
15
+ def load(cls, x: str, lora: dict[str, torch.Tensor], alpha: float, dora_scale: torch.Tensor) -> Optional["WeightAdapterBase"]:
16
+ raise NotImplementedError
17
+
18
+ def to_train(self) -> "WeightAdapterTrainBase":
19
+ raise NotImplementedError
20
+
21
+ @classmethod
22
+ def create_train(cls, weight, *args) -> "WeightAdapterTrainBase":
23
+ """
24
+ weight: The original weight tensor to be modified.
25
+ *args: Additional arguments for configuration, such as rank, alpha etc.
26
+ """
27
+ raise NotImplementedError
28
+
29
+ def calculate_weight(
30
+ self,
31
+ weight,
32
+ key,
33
+ strength,
34
+ strength_model,
35
+ offset,
36
+ function,
37
+ intermediate_dtype=torch.float32,
38
+ original_weight=None,
39
+ ):
40
+ raise NotImplementedError
41
+
42
+
43
+ class WeightAdapterTrainBase(nn.Module):
44
+ # We follow the scheme of PR #7032
45
+ def __init__(self):
46
+ super().__init__()
47
+
48
+ def __call__(self, w):
49
+ """
50
+ w: The original weight tensor to be modified.
51
+ """
52
+ raise NotImplementedError
53
+
54
+ def passive_memory_usage(self):
55
+ raise NotImplementedError("passive_memory_usage is not implemented")
56
+
57
+ def move_to(self, device):
58
+ self.to(device)
59
+ return self.passive_memory_usage()
60
+
61
+
62
+ def weight_decompose(dora_scale, weight, lora_diff, alpha, strength, intermediate_dtype, function):
63
+ dora_scale = memory_management.cast_to_device(dora_scale, weight.device, intermediate_dtype)
64
+ lora_diff *= alpha
65
+ weight_calc = weight + function(lora_diff).type(weight.dtype)
66
+
67
+ wd_on_output_axis = dora_scale.shape[0] == weight_calc.shape[0]
68
+ if wd_on_output_axis:
69
+ weight_norm = weight.reshape(weight.shape[0], -1).norm(dim=1, keepdim=True).reshape(weight.shape[0], *[1] * (weight.dim() - 1))
70
+ else:
71
+ weight_norm = weight_calc.transpose(0, 1).reshape(weight_calc.shape[1], -1).norm(dim=1, keepdim=True).reshape(weight_calc.shape[1], *[1] * (weight_calc.dim() - 1)).transpose(0, 1)
72
+ weight_norm = weight_norm + torch.finfo(weight.dtype).eps
73
+
74
+ weight_calc *= (dora_scale / weight_norm).type(weight.dtype)
75
+ if strength != 1.0:
76
+ weight_calc -= weight
77
+ weight += strength * (weight_calc)
78
+ else:
79
+ weight[:] = weight_calc
80
+ return weight
81
+
82
+
83
+ def pad_tensor_to_shape(tensor: torch.Tensor, new_shape: list[int]) -> torch.Tensor:
84
+ """
85
+ Pad a tensor to a new shape with zeros.
86
+
87
+ Args:
88
+ tensor (torch.Tensor): The original tensor to be padded.
89
+ new_shape (List[int]): The desired shape of the padded tensor.
90
+
91
+ Returns:
92
+ torch.Tensor: A new tensor padded with zeros to the specified shape.
93
+
94
+ Note:
95
+ If the new shape is smaller than the original tensor in any dimension,
96
+ the original tensor will be truncated in that dimension.
97
+ """
98
+ if any([new_shape[i] < tensor.shape[i] for i in range(len(new_shape))]):
99
+ raise ValueError("The new shape must be larger than the original tensor in all dimensions")
100
+
101
+ if len(new_shape) != len(tensor.shape):
102
+ raise ValueError("The new shape must have the same number of dimensions as the original tensor")
103
+
104
+ # Create a new tensor filled with zeros
105
+ padded_tensor = torch.zeros(new_shape, dtype=tensor.dtype, device=tensor.device)
106
+
107
+ # Create slicing tuples for both tensors
108
+ orig_slices = tuple(slice(0, dim) for dim in tensor.shape)
109
+ new_slices = tuple(slice(0, dim) for dim in tensor.shape)
110
+
111
+ # Copy the original tensor into the new tensor
112
+ padded_tensor[new_slices] = tensor[orig_slices]
113
+
114
+ return padded_tensor
115
+
116
+
117
+ def tucker_weight_from_conv(up, down, mid):
118
+ up = up.reshape(up.size(0), up.size(1))
119
+ down = down.reshape(down.size(0), down.size(1))
120
+ return torch.einsum("m n ..., i m, n j -> i j ...", mid, up, down)
121
+
122
+
123
+ def tucker_weight(wa, wb, t):
124
+ temp = torch.einsum("i j ..., j r -> i r ...", t, wb)
125
+ return torch.einsum("i j ..., i r -> r j ...", temp, wa)
126
+
127
+
128
+ def factorization(dimension: int, factor: int = -1) -> tuple[int, int]:
129
+ """
130
+ return a tuple of two value of input dimension decomposed by the number closest to factor
131
+ second value is higher or equal than first value.
132
+
133
+ examples)
134
+ factor
135
+ -1 2 4 8 16 ...
136
+ 127 -> 1, 127 127 -> 1, 127 127 -> 1, 127 127 -> 1, 127 127 -> 1, 127
137
+ 128 -> 8, 16 128 -> 2, 64 128 -> 4, 32 128 -> 8, 16 128 -> 8, 16
138
+ 250 -> 10, 25 250 -> 2, 125 250 -> 2, 125 250 -> 5, 50 250 -> 10, 25
139
+ 360 -> 8, 45 360 -> 2, 180 360 -> 4, 90 360 -> 8, 45 360 -> 12, 30
140
+ 512 -> 16, 32 512 -> 2, 256 512 -> 4, 128 512 -> 8, 64 512 -> 16, 32
141
+ 1024 -> 32, 32 1024 -> 2, 512 1024 -> 4, 256 1024 -> 8, 128 1024 -> 16, 64
142
+ """
143
+
144
+ if factor > 0 and (dimension % factor) == 0 and dimension >= factor**2:
145
+ m = factor
146
+ n = dimension // factor
147
+ if m > n:
148
+ n, m = m, n
149
+ return m, n
150
+ if factor < 0:
151
+ factor = dimension
152
+ m, n = 1, dimension
153
+ length = m + n
154
+ while m < n:
155
+ new_m = m + 1
156
+ while dimension % new_m != 0:
157
+ new_m += 1
158
+ new_n = dimension // new_m
159
+ if new_m + new_n > length or new_m > factor:
160
+ break
161
+ else:
162
+ m, n = new_m, new_n
163
+ if m > n:
164
+ n, m = m, n
165
+ return m, n
modules_forge/packages/comfy/weight_adapter/boft.py ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ from typing import Optional
3
+
4
+ import torch
5
+
6
+ from backend import memory_management
7
+
8
+ from .base import WeightAdapterBase, weight_decompose
9
+
10
+
11
+ class BOFTAdapter(WeightAdapterBase):
12
+ name = "boft"
13
+
14
+ def __init__(self, loaded_keys, weights):
15
+ self.loaded_keys = loaded_keys
16
+ self.weights = weights
17
+
18
+ @classmethod
19
+ def load(
20
+ cls,
21
+ x: str,
22
+ lora: dict[str, torch.Tensor],
23
+ alpha: float,
24
+ dora_scale: torch.Tensor,
25
+ loaded_keys: set[str] = None,
26
+ ) -> Optional["BOFTAdapter"]:
27
+ if loaded_keys is None:
28
+ loaded_keys = set()
29
+ blocks_name = "{}.oft_blocks".format(x)
30
+ rescale_name = "{}.rescale".format(x)
31
+
32
+ blocks = None
33
+ if blocks_name in lora.keys():
34
+ blocks = lora[blocks_name]
35
+ if blocks.ndim == 4:
36
+ loaded_keys.add(blocks_name)
37
+ else:
38
+ blocks = None
39
+ if blocks is None:
40
+ return None
41
+
42
+ rescale = None
43
+ if rescale_name in lora.keys():
44
+ rescale = lora[rescale_name]
45
+ loaded_keys.add(rescale_name)
46
+
47
+ weights = (blocks, rescale, alpha, dora_scale)
48
+ return cls(loaded_keys, weights)
49
+
50
+ def calculate_weight(
51
+ self,
52
+ weight,
53
+ key,
54
+ strength,
55
+ strength_model,
56
+ offset,
57
+ function,
58
+ intermediate_dtype=torch.float32,
59
+ original_weight=None,
60
+ ):
61
+ v = self.weights
62
+ blocks = v[0]
63
+ rescale = v[1]
64
+ alpha = v[2]
65
+ dora_scale = v[3]
66
+
67
+ blocks = memory_management.cast_to_device(blocks, weight.device, intermediate_dtype)
68
+ if rescale is not None:
69
+ rescale = memory_management.cast_to_device(rescale, weight.device, intermediate_dtype)
70
+
71
+ boft_m, block_num, boft_b, *_ = blocks.shape
72
+
73
+ try:
74
+ # Get r
75
+ I = torch.eye(boft_b, device=blocks.device, dtype=blocks.dtype)
76
+ # for Q = -Q^T
77
+ q = blocks - blocks.transpose(-1, -2)
78
+ normed_q = q
79
+ if alpha > 0: # alpha in boft/bboft is for constraint
80
+ q_norm = torch.norm(q) + 1e-8
81
+ if q_norm > alpha:
82
+ normed_q = q * alpha / q_norm
83
+ # use float() to prevent unsupported type in .inverse()
84
+ r = (I + normed_q) @ (I - normed_q).float().inverse()
85
+ r = r.to(weight)
86
+ inp = org = weight
87
+
88
+ r_b = boft_b // 2
89
+ for i in range(boft_m):
90
+ bi = r[i]
91
+ g = 2
92
+ k = 2**i * r_b
93
+ if strength != 1:
94
+ bi = bi * strength + (1 - strength) * I
95
+ inp = inp.unflatten(0, (-1, g, k)).transpose(1, 2).flatten(0, 2).unflatten(0, (-1, boft_b))
96
+ inp = torch.einsum("b i j, b j ...-> b i ...", bi, inp)
97
+ inp = inp.flatten(0, 1).unflatten(0, (-1, k, g)).transpose(1, 2).flatten(0, 2)
98
+
99
+ if rescale is not None:
100
+ inp = inp * rescale
101
+
102
+ lora_diff = inp - org
103
+ lora_diff = memory_management.cast_to_device(lora_diff, weight.device, intermediate_dtype)
104
+ if dora_scale is not None:
105
+ weight = weight_decompose(dora_scale, weight, lora_diff, alpha, strength, intermediate_dtype, function)
106
+ else:
107
+ weight += function((strength * lora_diff).type(weight.dtype))
108
+ except Exception as e:
109
+ logging.error("ERROR {} {} {}".format(self.name, key, e))
110
+ return weight
modules_forge/packages/comfy/weight_adapter/glora.py ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ from typing import Optional
3
+
4
+ import torch
5
+
6
+ from backend import memory_management
7
+
8
+ from .base import WeightAdapterBase, weight_decompose
9
+
10
+
11
+ class GLoRAAdapter(WeightAdapterBase):
12
+ name = "glora"
13
+
14
+ def __init__(self, loaded_keys, weights):
15
+ self.loaded_keys = loaded_keys
16
+ self.weights = weights
17
+
18
+ @classmethod
19
+ def load(
20
+ cls,
21
+ x: str,
22
+ lora: dict[str, torch.Tensor],
23
+ alpha: float,
24
+ dora_scale: torch.Tensor,
25
+ loaded_keys: set[str] = None,
26
+ ) -> Optional["GLoRAAdapter"]:
27
+ if loaded_keys is None:
28
+ loaded_keys = set()
29
+ a1_name = "{}.a1.weight".format(x)
30
+ a2_name = "{}.a2.weight".format(x)
31
+ b1_name = "{}.b1.weight".format(x)
32
+ b2_name = "{}.b2.weight".format(x)
33
+ if a1_name in lora:
34
+ weights = (lora[a1_name], lora[a2_name], lora[b1_name], lora[b2_name], alpha, dora_scale)
35
+ loaded_keys.add(a1_name)
36
+ loaded_keys.add(a2_name)
37
+ loaded_keys.add(b1_name)
38
+ loaded_keys.add(b2_name)
39
+ return cls(loaded_keys, weights)
40
+ else:
41
+ return None
42
+
43
+ def calculate_weight(
44
+ self,
45
+ weight,
46
+ key,
47
+ strength,
48
+ strength_model,
49
+ offset,
50
+ function,
51
+ intermediate_dtype=torch.float32,
52
+ original_weight=None,
53
+ ):
54
+ v = self.weights
55
+ dora_scale = v[5]
56
+
57
+ old_glora = False
58
+ if v[3].shape[1] == v[2].shape[0] == v[0].shape[0] == v[1].shape[1]:
59
+ rank = v[0].shape[0]
60
+ old_glora = True
61
+
62
+ if v[3].shape[0] == v[2].shape[1] == v[0].shape[1] == v[1].shape[0]:
63
+ if old_glora and v[1].shape[0] == weight.shape[0] and weight.shape[0] == weight.shape[1]:
64
+ pass
65
+ else:
66
+ old_glora = False
67
+ rank = v[1].shape[0]
68
+
69
+ a1 = memory_management.cast_to_device(v[0].flatten(start_dim=1), weight.device, intermediate_dtype)
70
+ a2 = memory_management.cast_to_device(v[1].flatten(start_dim=1), weight.device, intermediate_dtype)
71
+ b1 = memory_management.cast_to_device(v[2].flatten(start_dim=1), weight.device, intermediate_dtype)
72
+ b2 = memory_management.cast_to_device(v[3].flatten(start_dim=1), weight.device, intermediate_dtype)
73
+
74
+ if v[4] is not None:
75
+ alpha = v[4] / rank
76
+ else:
77
+ alpha = 1.0
78
+
79
+ try:
80
+ if old_glora:
81
+ lora_diff = (torch.mm(b2, b1) + torch.mm(torch.mm(weight.flatten(start_dim=1).to(dtype=intermediate_dtype), a2), a1)).reshape(weight.shape) # old lycoris glora
82
+ else:
83
+ if weight.dim() > 2:
84
+ lora_diff = torch.einsum("o i ..., i j -> o j ...", torch.einsum("o i ..., i j -> o j ...", weight.to(dtype=intermediate_dtype), a1), a2).reshape(weight.shape)
85
+ else:
86
+ lora_diff = torch.mm(torch.mm(weight.to(dtype=intermediate_dtype), a1), a2).reshape(weight.shape)
87
+ lora_diff += torch.mm(b1, b2).reshape(weight.shape)
88
+
89
+ if dora_scale is not None:
90
+ weight = weight_decompose(dora_scale, weight, lora_diff, alpha, strength, intermediate_dtype, function)
91
+ else:
92
+ weight += function(((strength * alpha) * lora_diff).type(weight.dtype))
93
+ except Exception as e:
94
+ logging.error("ERROR {} {} {}".format(self.name, key, e))
95
+ return weight
modules_forge/packages/comfy/weight_adapter/loha.py ADDED
@@ -0,0 +1,224 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ from typing import Optional
3
+
4
+ import torch
5
+
6
+ from backend import memory_management
7
+
8
+ from .base import WeightAdapterBase, WeightAdapterTrainBase, weight_decompose
9
+
10
+
11
+ class HadaWeight(torch.autograd.Function):
12
+ @staticmethod
13
+ def forward(ctx, w1u, w1d, w2u, w2d, scale=torch.tensor(1)):
14
+ ctx.save_for_backward(w1d, w1u, w2d, w2u, scale)
15
+ diff_weight = ((w1u @ w1d) * (w2u @ w2d)) * scale
16
+ return diff_weight
17
+
18
+ @staticmethod
19
+ def backward(ctx, grad_out):
20
+ (w1d, w1u, w2d, w2u, scale) = ctx.saved_tensors
21
+ grad_out = grad_out * scale
22
+ temp = grad_out * (w2u @ w2d)
23
+ grad_w1u = temp @ w1d.T
24
+ grad_w1d = w1u.T @ temp
25
+
26
+ temp = grad_out * (w1u @ w1d)
27
+ grad_w2u = temp @ w2d.T
28
+ grad_w2d = w2u.T @ temp
29
+
30
+ del temp
31
+ return grad_w1u, grad_w1d, grad_w2u, grad_w2d, None
32
+
33
+
34
+ class HadaWeightTucker(torch.autograd.Function):
35
+ @staticmethod
36
+ def forward(ctx, t1, w1u, w1d, t2, w2u, w2d, scale=torch.tensor(1)):
37
+ ctx.save_for_backward(t1, w1d, w1u, t2, w2d, w2u, scale)
38
+
39
+ rebuild1 = torch.einsum("i j ..., j r, i p -> p r ...", t1, w1d, w1u)
40
+ rebuild2 = torch.einsum("i j ..., j r, i p -> p r ...", t2, w2d, w2u)
41
+
42
+ return rebuild1 * rebuild2 * scale
43
+
44
+ @staticmethod
45
+ def backward(ctx, grad_out):
46
+ (t1, w1d, w1u, t2, w2d, w2u, scale) = ctx.saved_tensors
47
+ grad_out = grad_out * scale
48
+
49
+ temp = torch.einsum("i j ..., j r -> i r ...", t2, w2d)
50
+ rebuild = torch.einsum("i j ..., i r -> r j ...", temp, w2u)
51
+
52
+ grad_w = rebuild * grad_out
53
+ del rebuild
54
+
55
+ grad_w1u = torch.einsum("r j ..., i j ... -> r i", temp, grad_w)
56
+ grad_temp = torch.einsum("i j ..., i r -> r j ...", grad_w, w1u.T)
57
+ del grad_w, temp
58
+
59
+ grad_w1d = torch.einsum("i r ..., i j ... -> r j", t1, grad_temp)
60
+ grad_t1 = torch.einsum("i j ..., j r -> i r ...", grad_temp, w1d.T)
61
+ del grad_temp
62
+
63
+ temp = torch.einsum("i j ..., j r -> i r ...", t1, w1d)
64
+ rebuild = torch.einsum("i j ..., i r -> r j ...", temp, w1u)
65
+
66
+ grad_w = rebuild * grad_out
67
+ del rebuild
68
+
69
+ grad_w2u = torch.einsum("r j ..., i j ... -> r i", temp, grad_w)
70
+ grad_temp = torch.einsum("i j ..., i r -> r j ...", grad_w, w2u.T)
71
+ del grad_w, temp
72
+
73
+ grad_w2d = torch.einsum("i r ..., i j ... -> r j", t2, grad_temp)
74
+ grad_t2 = torch.einsum("i j ..., j r -> i r ...", grad_temp, w2d.T)
75
+ del grad_temp
76
+ return grad_t1, grad_w1u, grad_w1d, grad_t2, grad_w2u, grad_w2d, None
77
+
78
+
79
+ class LohaDiff(WeightAdapterTrainBase):
80
+ def __init__(self, weights):
81
+ super().__init__()
82
+ # Unpack weights tuple from LoHaAdapter
83
+ w1a, w1b, alpha, w2a, w2b, t1, t2, _ = weights
84
+
85
+ # Create trainable parameters
86
+ self.hada_w1_a = torch.nn.Parameter(w1a)
87
+ self.hada_w1_b = torch.nn.Parameter(w1b)
88
+ self.hada_w2_a = torch.nn.Parameter(w2a)
89
+ self.hada_w2_b = torch.nn.Parameter(w2b)
90
+
91
+ self.use_tucker = False
92
+ if t1 is not None and t2 is not None:
93
+ self.use_tucker = True
94
+ self.hada_t1 = torch.nn.Parameter(t1)
95
+ self.hada_t2 = torch.nn.Parameter(t2)
96
+ else:
97
+ # Keep the attributes for consistent access
98
+ self.hada_t1 = None
99
+ self.hada_t2 = None
100
+
101
+ # Store rank and non-trainable alpha
102
+ self.rank = w1b.shape[0]
103
+ self.alpha = torch.nn.Parameter(torch.tensor(alpha), requires_grad=False)
104
+
105
+ def __call__(self, w):
106
+ org_dtype = w.dtype
107
+
108
+ scale = self.alpha / self.rank
109
+ if self.use_tucker:
110
+ diff_weight = HadaWeightTucker.apply(self.hada_t1, self.hada_w1_a, self.hada_w1_b, self.hada_t2, self.hada_w2_a, self.hada_w2_b, scale)
111
+ else:
112
+ diff_weight = HadaWeight.apply(self.hada_w1_a, self.hada_w1_b, self.hada_w2_a, self.hada_w2_b, scale)
113
+
114
+ # Add the scaled difference to the original weight
115
+ weight = w.to(diff_weight) + diff_weight.reshape(w.shape)
116
+
117
+ return weight.to(org_dtype)
118
+
119
+ def passive_memory_usage(self):
120
+ """Calculates memory usage of the trainable parameters."""
121
+ return sum(param.numel() * param.element_size() for param in self.parameters())
122
+
123
+
124
+ class LoHaAdapter(WeightAdapterBase):
125
+ name = "loha"
126
+
127
+ def __init__(self, loaded_keys, weights):
128
+ self.loaded_keys = loaded_keys
129
+ self.weights = weights
130
+
131
+ @classmethod
132
+ def create_train(cls, weight, rank=1, alpha=1.0):
133
+ out_dim = weight.shape[0]
134
+ in_dim = weight.shape[1:].numel()
135
+ mat1 = torch.empty(out_dim, rank, device=weight.device, dtype=torch.float32)
136
+ mat2 = torch.empty(rank, in_dim, device=weight.device, dtype=torch.float32)
137
+ torch.nn.init.normal_(mat1, 0.1)
138
+ torch.nn.init.constant_(mat2, 0.0)
139
+ mat3 = torch.empty(out_dim, rank, device=weight.device, dtype=torch.float32)
140
+ mat4 = torch.empty(rank, in_dim, device=weight.device, dtype=torch.float32)
141
+ torch.nn.init.normal_(mat3, 0.1)
142
+ torch.nn.init.normal_(mat4, 0.01)
143
+ return LohaDiff((mat1, mat2, alpha, mat3, mat4, None, None, None))
144
+
145
+ def to_train(self):
146
+ return LohaDiff(self.weights)
147
+
148
+ @classmethod
149
+ def load(
150
+ cls,
151
+ x: str,
152
+ lora: dict[str, torch.Tensor],
153
+ alpha: float,
154
+ dora_scale: torch.Tensor,
155
+ loaded_keys: set[str] = None,
156
+ ) -> Optional["LoHaAdapter"]:
157
+ if loaded_keys is None:
158
+ loaded_keys = set()
159
+
160
+ hada_w1_a_name = "{}.hada_w1_a".format(x)
161
+ hada_w1_b_name = "{}.hada_w1_b".format(x)
162
+ hada_w2_a_name = "{}.hada_w2_a".format(x)
163
+ hada_w2_b_name = "{}.hada_w2_b".format(x)
164
+ hada_t1_name = "{}.hada_t1".format(x)
165
+ hada_t2_name = "{}.hada_t2".format(x)
166
+ if hada_w1_a_name in lora.keys():
167
+ hada_t1 = None
168
+ hada_t2 = None
169
+ if hada_t1_name in lora.keys():
170
+ hada_t1 = lora[hada_t1_name]
171
+ hada_t2 = lora[hada_t2_name]
172
+ loaded_keys.add(hada_t1_name)
173
+ loaded_keys.add(hada_t2_name)
174
+
175
+ weights = (lora[hada_w1_a_name], lora[hada_w1_b_name], alpha, lora[hada_w2_a_name], lora[hada_w2_b_name], hada_t1, hada_t2, dora_scale)
176
+ loaded_keys.add(hada_w1_a_name)
177
+ loaded_keys.add(hada_w1_b_name)
178
+ loaded_keys.add(hada_w2_a_name)
179
+ loaded_keys.add(hada_w2_b_name)
180
+ return cls(loaded_keys, weights)
181
+ else:
182
+ return None
183
+
184
+ def calculate_weight(
185
+ self,
186
+ weight,
187
+ key,
188
+ strength,
189
+ strength_model,
190
+ offset,
191
+ function,
192
+ intermediate_dtype=torch.float32,
193
+ original_weight=None,
194
+ ):
195
+ v = self.weights
196
+ w1a = v[0]
197
+ w1b = v[1]
198
+ if v[2] is not None:
199
+ alpha = v[2] / w1b.shape[0]
200
+ else:
201
+ alpha = 1.0
202
+
203
+ w2a = v[3]
204
+ w2b = v[4]
205
+ dora_scale = v[7]
206
+ if v[5] is not None: # cp decomposition
207
+ t1 = v[5]
208
+ t2 = v[6]
209
+ m1 = torch.einsum("i j k l, j r, i p -> p r k l", memory_management.cast_to_device(t1, weight.device, intermediate_dtype), memory_management.cast_to_device(w1b, weight.device, intermediate_dtype), memory_management.cast_to_device(w1a, weight.device, intermediate_dtype))
210
+
211
+ m2 = torch.einsum("i j k l, j r, i p -> p r k l", memory_management.cast_to_device(t2, weight.device, intermediate_dtype), memory_management.cast_to_device(w2b, weight.device, intermediate_dtype), memory_management.cast_to_device(w2a, weight.device, intermediate_dtype))
212
+ else:
213
+ m1 = torch.mm(memory_management.cast_to_device(w1a, weight.device, intermediate_dtype), memory_management.cast_to_device(w1b, weight.device, intermediate_dtype))
214
+ m2 = torch.mm(memory_management.cast_to_device(w2a, weight.device, intermediate_dtype), memory_management.cast_to_device(w2b, weight.device, intermediate_dtype))
215
+
216
+ try:
217
+ lora_diff = (m1 * m2).reshape(weight.shape)
218
+ if dora_scale is not None:
219
+ weight = weight_decompose(dora_scale, weight, lora_diff, alpha, strength, intermediate_dtype, function)
220
+ else:
221
+ weight += function(((strength * alpha) * lora_diff).type(weight.dtype))
222
+ except Exception as e:
223
+ logging.error("ERROR {} {} {}".format(self.name, key, e))
224
+ return weight
modules_forge/packages/comfy/weight_adapter/lokr.py ADDED
@@ -0,0 +1,210 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ from typing import Optional
3
+
4
+ import torch
5
+
6
+ from backend import memory_management
7
+
8
+ from .base import (
9
+ WeightAdapterBase,
10
+ WeightAdapterTrainBase,
11
+ factorization,
12
+ weight_decompose,
13
+ )
14
+
15
+
16
+ class LokrDiff(WeightAdapterTrainBase):
17
+ def __init__(self, weights):
18
+ super().__init__()
19
+ (lokr_w1, lokr_w2, alpha, lokr_w1_a, lokr_w1_b, lokr_w2_a, lokr_w2_b, lokr_t2, dora_scale) = weights
20
+ self.use_tucker = False
21
+ if lokr_w1_a is not None:
22
+ _, rank_a = lokr_w1_a.shape[0], lokr_w1_a.shape[1]
23
+ rank_a, _ = lokr_w1_b.shape[0], lokr_w1_b.shape[1]
24
+ self.lokr_w1_a = torch.nn.Parameter(lokr_w1_a)
25
+ self.lokr_w1_b = torch.nn.Parameter(lokr_w1_b)
26
+ self.w1_rebuild = True
27
+ self.ranka = rank_a
28
+
29
+ if lokr_w2_a is not None:
30
+ _, rank_b = lokr_w2_a.shape[0], lokr_w2_a.shape[1]
31
+ rank_b, _ = lokr_w2_b.shape[0], lokr_w2_b.shape[1]
32
+ self.lokr_w2_a = torch.nn.Parameter(lokr_w2_a)
33
+ self.lokr_w2_b = torch.nn.Parameter(lokr_w2_b)
34
+ if lokr_t2 is not None:
35
+ self.use_tucker = True
36
+ self.lokr_t2 = torch.nn.Parameter(lokr_t2)
37
+ self.w2_rebuild = True
38
+ self.rankb = rank_b
39
+
40
+ if lokr_w1 is not None:
41
+ self.lokr_w1 = torch.nn.Parameter(lokr_w1)
42
+ self.w1_rebuild = False
43
+
44
+ if lokr_w2 is not None:
45
+ self.lokr_w2 = torch.nn.Parameter(lokr_w2)
46
+ self.w2_rebuild = False
47
+
48
+ self.alpha = torch.nn.Parameter(torch.tensor(alpha), requires_grad=False)
49
+
50
+ @property
51
+ def w1(self):
52
+ if self.w1_rebuild:
53
+ return (self.lokr_w1_a @ self.lokr_w1_b) * (self.alpha / self.ranka)
54
+ else:
55
+ return self.lokr_w1
56
+
57
+ @property
58
+ def w2(self):
59
+ if self.w2_rebuild:
60
+ if self.use_tucker:
61
+ w2 = torch.einsum("i j k l, j r, i p -> p r k l", self.lokr_t2, self.lokr_w2_b, self.lokr_w2_a)
62
+ else:
63
+ w2 = self.lokr_w2_a @ self.lokr_w2_b
64
+ return w2 * (self.alpha / self.rankb)
65
+ else:
66
+ return self.lokr_w2
67
+
68
+ def __call__(self, w):
69
+ diff = torch.kron(self.w1, self.w2)
70
+ return w + diff.reshape(w.shape).to(w)
71
+
72
+ def passive_memory_usage(self):
73
+ return sum(param.numel() * param.element_size() for param in self.parameters())
74
+
75
+
76
+ class LoKrAdapter(WeightAdapterBase):
77
+ name = "lokr"
78
+
79
+ def __init__(self, loaded_keys, weights):
80
+ self.loaded_keys = loaded_keys
81
+ self.weights = weights
82
+
83
+ @classmethod
84
+ def create_train(cls, weight, rank=1, alpha=1.0):
85
+ out_dim = weight.shape[0]
86
+ in_dim = weight.shape[1:].numel()
87
+ out1, out2 = factorization(out_dim, rank)
88
+ in1, in2 = factorization(in_dim, rank)
89
+ mat1 = torch.empty(out1, in1, device=weight.device, dtype=torch.float32)
90
+ mat2 = torch.empty(out2, in2, device=weight.device, dtype=torch.float32)
91
+ torch.nn.init.kaiming_uniform_(mat2, a=5**0.5)
92
+ torch.nn.init.constant_(mat1, 0.0)
93
+ return LokrDiff((mat1, mat2, alpha, None, None, None, None, None, None))
94
+
95
+ def to_train(self):
96
+ return LokrDiff(self.weights)
97
+
98
+ @classmethod
99
+ def load(
100
+ cls,
101
+ x: str,
102
+ lora: dict[str, torch.Tensor],
103
+ alpha: float,
104
+ dora_scale: torch.Tensor,
105
+ loaded_keys: set[str] = None,
106
+ ) -> Optional["LoKrAdapter"]:
107
+ if loaded_keys is None:
108
+ loaded_keys = set()
109
+ lokr_w1_name = "{}.lokr_w1".format(x)
110
+ lokr_w2_name = "{}.lokr_w2".format(x)
111
+ lokr_w1_a_name = "{}.lokr_w1_a".format(x)
112
+ lokr_w1_b_name = "{}.lokr_w1_b".format(x)
113
+ lokr_t2_name = "{}.lokr_t2".format(x)
114
+ lokr_w2_a_name = "{}.lokr_w2_a".format(x)
115
+ lokr_w2_b_name = "{}.lokr_w2_b".format(x)
116
+
117
+ lokr_w1 = None
118
+ if lokr_w1_name in lora.keys():
119
+ lokr_w1 = lora[lokr_w1_name]
120
+ loaded_keys.add(lokr_w1_name)
121
+
122
+ lokr_w2 = None
123
+ if lokr_w2_name in lora.keys():
124
+ lokr_w2 = lora[lokr_w2_name]
125
+ loaded_keys.add(lokr_w2_name)
126
+
127
+ lokr_w1_a = None
128
+ if lokr_w1_a_name in lora.keys():
129
+ lokr_w1_a = lora[lokr_w1_a_name]
130
+ loaded_keys.add(lokr_w1_a_name)
131
+
132
+ lokr_w1_b = None
133
+ if lokr_w1_b_name in lora.keys():
134
+ lokr_w1_b = lora[lokr_w1_b_name]
135
+ loaded_keys.add(lokr_w1_b_name)
136
+
137
+ lokr_w2_a = None
138
+ if lokr_w2_a_name in lora.keys():
139
+ lokr_w2_a = lora[lokr_w2_a_name]
140
+ loaded_keys.add(lokr_w2_a_name)
141
+
142
+ lokr_w2_b = None
143
+ if lokr_w2_b_name in lora.keys():
144
+ lokr_w2_b = lora[lokr_w2_b_name]
145
+ loaded_keys.add(lokr_w2_b_name)
146
+
147
+ lokr_t2 = None
148
+ if lokr_t2_name in lora.keys():
149
+ lokr_t2 = lora[lokr_t2_name]
150
+ loaded_keys.add(lokr_t2_name)
151
+
152
+ if (lokr_w1 is not None) or (lokr_w2 is not None) or (lokr_w1_a is not None) or (lokr_w2_a is not None):
153
+ weights = (lokr_w1, lokr_w2, alpha, lokr_w1_a, lokr_w1_b, lokr_w2_a, lokr_w2_b, lokr_t2, dora_scale)
154
+ return cls(loaded_keys, weights)
155
+ else:
156
+ return None
157
+
158
+ def calculate_weight(
159
+ self,
160
+ weight,
161
+ key,
162
+ strength,
163
+ strength_model,
164
+ offset,
165
+ function,
166
+ intermediate_dtype=torch.float32,
167
+ original_weight=None,
168
+ ):
169
+ v = self.weights
170
+ w1 = v[0]
171
+ w2 = v[1]
172
+ w1_a = v[3]
173
+ w1_b = v[4]
174
+ w2_a = v[5]
175
+ w2_b = v[6]
176
+ t2 = v[7]
177
+ dora_scale = v[8]
178
+ dim = None
179
+
180
+ if w1 is None:
181
+ dim = w1_b.shape[0]
182
+ w1 = torch.mm(memory_management.cast_to_device(w1_a, weight.device, intermediate_dtype), memory_management.cast_to_device(w1_b, weight.device, intermediate_dtype))
183
+ else:
184
+ w1 = memory_management.cast_to_device(w1, weight.device, intermediate_dtype)
185
+
186
+ if w2 is None:
187
+ dim = w2_b.shape[0]
188
+ if t2 is None:
189
+ w2 = torch.mm(memory_management.cast_to_device(w2_a, weight.device, intermediate_dtype), memory_management.cast_to_device(w2_b, weight.device, intermediate_dtype))
190
+ else:
191
+ w2 = torch.einsum("i j k l, j r, i p -> p r k l", memory_management.cast_to_device(t2, weight.device, intermediate_dtype), memory_management.cast_to_device(w2_b, weight.device, intermediate_dtype), memory_management.cast_to_device(w2_a, weight.device, intermediate_dtype))
192
+ else:
193
+ w2 = memory_management.cast_to_device(w2, weight.device, intermediate_dtype)
194
+
195
+ if len(w2.shape) == 4:
196
+ w1 = w1.unsqueeze(2).unsqueeze(2)
197
+ if v[2] is not None and dim is not None:
198
+ alpha = v[2] / dim
199
+ else:
200
+ alpha = 1.0
201
+
202
+ try:
203
+ lora_diff = torch.kron(w1, w2).reshape(weight.shape)
204
+ if dora_scale is not None:
205
+ weight = weight_decompose(dora_scale, weight, lora_diff, alpha, strength, intermediate_dtype, function)
206
+ else:
207
+ weight += function(((strength * alpha) * lora_diff).type(weight.dtype))
208
+ except Exception as e:
209
+ logging.error("ERROR {} {} {}".format(self.name, key, e))
210
+ return weight
modules_forge/packages/comfy/weight_adapter/lora.py ADDED
@@ -0,0 +1,198 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ from typing import Optional
3
+
4
+ import torch
5
+
6
+ from backend import memory_management
7
+
8
+ from .base import (
9
+ WeightAdapterBase,
10
+ WeightAdapterTrainBase,
11
+ pad_tensor_to_shape,
12
+ tucker_weight_from_conv,
13
+ weight_decompose,
14
+ )
15
+
16
+
17
+ class LoraDiff(WeightAdapterTrainBase):
18
+ def __init__(self, weights):
19
+ super().__init__()
20
+ mat1, mat2, alpha, mid, dora_scale, reshape = weights
21
+ out_dim, rank = mat1.shape[0], mat1.shape[1]
22
+ rank, in_dim = mat2.shape[0], mat2.shape[1]
23
+ if mid is not None:
24
+ convdim = mid.ndim - 2
25
+ layer = (torch.nn.Conv1d, torch.nn.Conv2d, torch.nn.Conv3d)[convdim]
26
+ else:
27
+ layer = torch.nn.Linear
28
+ self.lora_up = layer(rank, out_dim, bias=False)
29
+ self.lora_down = layer(in_dim, rank, bias=False)
30
+ self.lora_up.weight.data.copy_(mat1)
31
+ self.lora_down.weight.data.copy_(mat2)
32
+ if mid is not None:
33
+ self.lora_mid = layer(mid, rank, bias=False)
34
+ self.lora_mid.weight.data.copy_(mid)
35
+ else:
36
+ self.lora_mid = None
37
+ self.rank = rank
38
+ self.alpha = torch.nn.Parameter(torch.tensor(alpha), requires_grad=False)
39
+
40
+ def __call__(self, w):
41
+ org_dtype = w.dtype
42
+ if self.lora_mid is None:
43
+ diff = self.lora_up.weight @ self.lora_down.weight
44
+ else:
45
+ diff = tucker_weight_from_conv(self.lora_up.weight, self.lora_down.weight, self.lora_mid.weight)
46
+ scale = self.alpha / self.rank
47
+ weight = w + scale * diff.reshape(w.shape)
48
+ return weight.to(org_dtype)
49
+
50
+ def passive_memory_usage(self):
51
+ return sum(param.numel() * param.element_size() for param in self.parameters())
52
+
53
+
54
+ class LoRAAdapter(WeightAdapterBase):
55
+ name = "lora"
56
+
57
+ def __init__(self, loaded_keys, weights):
58
+ self.loaded_keys = loaded_keys
59
+ self.weights = weights
60
+
61
+ @classmethod
62
+ def create_train(cls, weight, rank=1, alpha=1.0):
63
+ out_dim = weight.shape[0]
64
+ in_dim = weight.shape[1:].numel()
65
+ mat1 = torch.empty(out_dim, rank, device=weight.device, dtype=torch.float32)
66
+ mat2 = torch.empty(rank, in_dim, device=weight.device, dtype=torch.float32)
67
+ torch.nn.init.kaiming_uniform_(mat1, a=5**0.5)
68
+ torch.nn.init.constant_(mat2, 0.0)
69
+ return LoraDiff((mat1, mat2, alpha, None, None, None))
70
+
71
+ def to_train(self):
72
+ return LoraDiff(self.weights)
73
+
74
+ @classmethod
75
+ def load(
76
+ cls,
77
+ x: str,
78
+ lora: dict[str, torch.Tensor],
79
+ alpha: float,
80
+ dora_scale: torch.Tensor,
81
+ loaded_keys: set[str] = None,
82
+ ) -> Optional["LoRAAdapter"]:
83
+ if loaded_keys is None:
84
+ loaded_keys = set()
85
+
86
+ reshape_name = "{}.reshape_weight".format(x)
87
+ regular_lora = "{}.lora_up.weight".format(x)
88
+ diffusers_lora = "{}_lora.up.weight".format(x)
89
+ diffusers2_lora = "{}.lora_B.weight".format(x)
90
+ diffusers3_lora = "{}.lora.up.weight".format(x)
91
+ mochi_lora = "{}.lora_B".format(x)
92
+ transformers_lora = "{}.lora_linear_layer.up.weight".format(x)
93
+ qwen_default_lora = "{}.lora_B.default.weight".format(x)
94
+ A_name = None
95
+
96
+ if regular_lora in lora.keys():
97
+ A_name = regular_lora
98
+ B_name = "{}.lora_down.weight".format(x)
99
+ mid_name = "{}.lora_mid.weight".format(x)
100
+ elif diffusers_lora in lora.keys():
101
+ A_name = diffusers_lora
102
+ B_name = "{}_lora.down.weight".format(x)
103
+ mid_name = None
104
+ elif diffusers2_lora in lora.keys():
105
+ A_name = diffusers2_lora
106
+ B_name = "{}.lora_A.weight".format(x)
107
+ mid_name = None
108
+ elif diffusers3_lora in lora.keys():
109
+ A_name = diffusers3_lora
110
+ B_name = "{}.lora.down.weight".format(x)
111
+ mid_name = None
112
+ elif mochi_lora in lora.keys():
113
+ A_name = mochi_lora
114
+ B_name = "{}.lora_A".format(x)
115
+ mid_name = None
116
+ elif transformers_lora in lora.keys():
117
+ A_name = transformers_lora
118
+ B_name = "{}.lora_linear_layer.down.weight".format(x)
119
+ mid_name = None
120
+ elif qwen_default_lora in lora.keys():
121
+ A_name = qwen_default_lora
122
+ B_name = "{}.lora_A.default.weight".format(x)
123
+ mid_name = None
124
+
125
+ if A_name is not None:
126
+ mid = None
127
+ if mid_name is not None and mid_name in lora.keys():
128
+ mid = lora[mid_name]
129
+ loaded_keys.add(mid_name)
130
+ reshape = None
131
+ if reshape_name in lora.keys():
132
+ try:
133
+ reshape = lora[reshape_name].tolist()
134
+ loaded_keys.add(reshape_name)
135
+ except:
136
+ pass
137
+ weights = (lora[A_name], lora[B_name], alpha, mid, dora_scale, reshape)
138
+ loaded_keys.add(A_name)
139
+ loaded_keys.add(B_name)
140
+ return cls(loaded_keys, weights)
141
+ else:
142
+ return None
143
+
144
+ def calculate_weight(
145
+ self,
146
+ weight,
147
+ key,
148
+ strength,
149
+ strength_model,
150
+ offset,
151
+ function,
152
+ intermediate_dtype=torch.float32,
153
+ original_weight=None,
154
+ ):
155
+ v = self.weights
156
+ mat1 = memory_management.cast_to_device(v[0], weight.device, intermediate_dtype)
157
+ mat2 = memory_management.cast_to_device(v[1], weight.device, intermediate_dtype)
158
+ dora_scale = v[4]
159
+ reshape = v[5]
160
+
161
+ if reshape is not None:
162
+ weight = pad_tensor_to_shape(weight, reshape)
163
+
164
+ if v[2] is not None:
165
+ alpha = v[2] / mat2.shape[0]
166
+ else:
167
+ alpha = 1.0
168
+
169
+ if v[3] is not None:
170
+ # locon mid weights, hopefully the math is fine because I didn't properly test it
171
+ mat3 = memory_management.cast_to_device(v[3], weight.device, intermediate_dtype)
172
+ final_shape = [mat2.shape[1], mat2.shape[0], mat3.shape[2], mat3.shape[3]]
173
+ mat2 = (
174
+ torch.mm(
175
+ mat2.transpose(0, 1).flatten(start_dim=1),
176
+ mat3.transpose(0, 1).flatten(start_dim=1),
177
+ )
178
+ .reshape(final_shape)
179
+ .transpose(0, 1)
180
+ )
181
+ try:
182
+ lora_diff = torch.mm(mat1.flatten(start_dim=1), mat2.flatten(start_dim=1)).reshape(weight.shape)
183
+ del mat1, mat2
184
+ if dora_scale is not None:
185
+ weight = weight_decompose(
186
+ dora_scale,
187
+ weight,
188
+ lora_diff,
189
+ alpha,
190
+ strength,
191
+ intermediate_dtype,
192
+ function,
193
+ )
194
+ else:
195
+ weight += function(((strength * alpha) * lora_diff).type(weight.dtype))
196
+ except Exception as e:
197
+ logging.error("ERROR {} {} {}".format(self.name, key, e))
198
+ return weight
modules_forge/packages/comfy/weight_adapter/oft.py ADDED
@@ -0,0 +1,166 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ from typing import Optional
3
+
4
+ import torch
5
+
6
+ from backend import memory_management
7
+
8
+ from .base import (
9
+ WeightAdapterBase,
10
+ WeightAdapterTrainBase,
11
+ factorization,
12
+ weight_decompose,
13
+ )
14
+
15
+
16
+ class OFTDiff(WeightAdapterTrainBase):
17
+ def __init__(self, weights):
18
+ super().__init__()
19
+ # Unpack weights tuple from LoHaAdapter
20
+ blocks, rescale, alpha, _ = weights
21
+
22
+ # Create trainable parameters
23
+ self.oft_blocks = torch.nn.Parameter(blocks)
24
+ if rescale is not None:
25
+ self.rescale = torch.nn.Parameter(rescale)
26
+ self.rescaled = True
27
+ else:
28
+ self.rescaled = False
29
+ self.block_num, self.block_size, _ = blocks.shape
30
+ self.constraint = float(alpha)
31
+ self.alpha = torch.nn.Parameter(torch.tensor(alpha), requires_grad=False)
32
+
33
+ def __call__(self, w):
34
+ org_dtype = w.dtype
35
+ I = torch.eye(self.block_size, device=self.oft_blocks.device)
36
+
37
+ ## generate r
38
+ # for Q = -Q^T
39
+ q = self.oft_blocks - self.oft_blocks.transpose(1, 2)
40
+ normed_q = q
41
+ if self.constraint:
42
+ q_norm = torch.norm(q) + 1e-8
43
+ if q_norm > self.constraint:
44
+ normed_q = q * self.constraint / q_norm
45
+ # use float() to prevent unsupported type
46
+ r = (I + normed_q) @ (I - normed_q).float().inverse()
47
+
48
+ ## Apply chunked matmul on weight
49
+ _, *shape = w.shape
50
+ org_weight = w.to(dtype=r.dtype)
51
+ org_weight = org_weight.unflatten(0, (self.block_num, self.block_size))
52
+ # Init R=0, so add I on it to ensure the output of step0 is original model output
53
+ weight = torch.einsum(
54
+ "k n m, k n ... -> k m ...",
55
+ r,
56
+ org_weight,
57
+ ).flatten(0, 1)
58
+ if self.rescaled:
59
+ weight = self.rescale * weight
60
+ return weight.to(org_dtype)
61
+
62
+ def passive_memory_usage(self):
63
+ """Calculates memory usage of the trainable parameters."""
64
+ return sum(param.numel() * param.element_size() for param in self.parameters())
65
+
66
+
67
+ class OFTAdapter(WeightAdapterBase):
68
+ name = "oft"
69
+
70
+ def __init__(self, loaded_keys, weights):
71
+ self.loaded_keys = loaded_keys
72
+ self.weights = weights
73
+
74
+ @classmethod
75
+ def create_train(cls, weight, rank=1, alpha=1.0):
76
+ out_dim = weight.shape[0]
77
+ block_size, block_num = factorization(out_dim, rank)
78
+ block = torch.zeros(block_num, block_size, block_size, device=weight.device, dtype=torch.float32)
79
+ return OFTDiff((block, None, alpha, None))
80
+
81
+ def to_train(self):
82
+ return OFTDiff(self.weights)
83
+
84
+ @classmethod
85
+ def load(
86
+ cls,
87
+ x: str,
88
+ lora: dict[str, torch.Tensor],
89
+ alpha: float,
90
+ dora_scale: torch.Tensor,
91
+ loaded_keys: set[str] = None,
92
+ ) -> Optional["OFTAdapter"]:
93
+ if loaded_keys is None:
94
+ loaded_keys = set()
95
+ blocks_name = "{}.oft_blocks".format(x)
96
+ rescale_name = "{}.rescale".format(x)
97
+
98
+ blocks = None
99
+ if blocks_name in lora.keys():
100
+ blocks = lora[blocks_name]
101
+ if blocks.ndim == 3:
102
+ loaded_keys.add(blocks_name)
103
+ else:
104
+ blocks = None
105
+ if blocks is None:
106
+ return None
107
+
108
+ rescale = None
109
+ if rescale_name in lora.keys():
110
+ rescale = lora[rescale_name]
111
+ loaded_keys.add(rescale_name)
112
+
113
+ weights = (blocks, rescale, alpha, dora_scale)
114
+ return cls(loaded_keys, weights)
115
+
116
+ def calculate_weight(
117
+ self,
118
+ weight,
119
+ key,
120
+ strength,
121
+ strength_model,
122
+ offset,
123
+ function,
124
+ intermediate_dtype=torch.float32,
125
+ original_weight=None,
126
+ ):
127
+ v = self.weights
128
+ blocks = v[0]
129
+ rescale = v[1]
130
+ alpha = v[2]
131
+ if alpha is None:
132
+ alpha = 0
133
+ dora_scale = v[3]
134
+
135
+ blocks = memory_management.cast_to_device(blocks, weight.device, intermediate_dtype)
136
+ if rescale is not None:
137
+ rescale = memory_management.cast_to_device(rescale, weight.device, intermediate_dtype)
138
+
139
+ block_num, block_size, *_ = blocks.shape
140
+
141
+ try:
142
+ # Get r
143
+ I = torch.eye(block_size, device=blocks.device, dtype=blocks.dtype)
144
+ # for Q = -Q^T
145
+ q = blocks - blocks.transpose(1, 2)
146
+ normed_q = q
147
+ if alpha > 0: # alpha in oft/boft is for constraint
148
+ q_norm = torch.norm(q) + 1e-8
149
+ if q_norm > alpha:
150
+ normed_q = q * alpha / q_norm
151
+ # use float() to prevent unsupported type in .inverse()
152
+ r = (I + normed_q) @ (I - normed_q).float().inverse()
153
+ r = r.to(weight)
154
+ _, *shape = weight.shape
155
+ lora_diff = torch.einsum(
156
+ "k n m, k n ... -> k m ...",
157
+ (r * strength) - strength * I,
158
+ weight.view(block_num, block_size, *shape),
159
+ ).view(-1, *shape)
160
+ if dora_scale is not None:
161
+ weight = weight_decompose(dora_scale, weight, lora_diff, alpha, strength, intermediate_dtype, function)
162
+ else:
163
+ weight += function((strength * lora_diff).type(weight.dtype))
164
+ except Exception as e:
165
+ logging.error("ERROR {} {} {}".format(self.name, key, e))
166
+ return weight
modules_forge/packages/comfy/weight_adapter/oftv2.py ADDED
@@ -0,0 +1,196 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ from typing import Optional
3
+
4
+ import torch
5
+
6
+ from .base import WeightAdapterBase, weight_decompose
7
+
8
+
9
+ class OFTRotationUtil:
10
+ def __init__(
11
+ self,
12
+ weight: torch.Tensor,
13
+ block_size: int,
14
+ coft: bool = False,
15
+ eps: float = 6e-5,
16
+ use_cayley_neumann: bool = True,
17
+ num_cayley_neumann_terms: int = 5,
18
+ ):
19
+ self.weight = weight
20
+ self.block_size = block_size
21
+ self.coft = coft
22
+ self.eps = eps
23
+ self.use_cayley_neumann = use_cayley_neumann
24
+ self.num_cayley_neumann_terms = num_cayley_neumann_terms
25
+ self.rows, self.cols = torch.triu_indices(self.block_size, self.block_size, 1)
26
+
27
+ def _get_triu_indices(self, device):
28
+ if self.rows.device != device:
29
+ self.rows = self.rows.to(device)
30
+ self.cols = self.cols.to(device)
31
+ return self.rows, self.cols
32
+
33
+ def _pytorch_skew_symmetric(self, vec: torch.Tensor) -> torch.Tensor:
34
+ batch_size = vec.shape[0]
35
+ matrix = torch.zeros(batch_size, self.block_size, self.block_size, device=vec.device, dtype=vec.dtype)
36
+ rows, cols = self._get_triu_indices(vec.device)
37
+ matrix[:, rows, cols] = vec
38
+ matrix = matrix - matrix.transpose(-2, -1)
39
+ return matrix
40
+
41
+ def _pytorch_skew_symmetric_inv(self, matrix: torch.Tensor) -> torch.Tensor:
42
+ rows, cols = self._get_triu_indices(matrix.device)
43
+ vec = matrix[:, rows, cols]
44
+ return vec
45
+
46
+ def _project_batch(self) -> torch.Tensor:
47
+ oft_R = self._pytorch_skew_symmetric(self.weight)
48
+ eps = self.eps * (1 / torch.sqrt(torch.tensor(oft_R.shape[0], device=oft_R.device)))
49
+ origin_matrix = torch.zeros_like(oft_R)
50
+ diff = oft_R - origin_matrix
51
+ norm_diff = torch.norm(diff, dim=(1, 2), keepdim=True)
52
+ mask = (norm_diff <= eps).bool()
53
+ out = torch.where(mask, oft_R, origin_matrix + eps * (diff / norm_diff))
54
+ return self._pytorch_skew_symmetric_inv(out)
55
+
56
+ def _cayley_batch(self, Q: torch.Tensor) -> torch.Tensor:
57
+ b, _ = Q.shape
58
+ previous_dtype = Q.dtype
59
+ Q_skew = self._pytorch_skew_symmetric(Q)
60
+ if self.use_cayley_neumann:
61
+ R = torch.eye(self.block_size, device=Q.device, dtype=Q.dtype).repeat(b, 1, 1)
62
+ if self.num_cayley_neumann_terms > 1:
63
+ R.add_(Q_skew, alpha=2.0)
64
+ if self.num_cayley_neumann_terms > 2:
65
+ Q_squared = torch.bmm(Q_skew, Q_skew)
66
+ R.add_(Q_squared, alpha=2.0)
67
+ Q_power = Q_squared
68
+ for _ in range(3, self.num_cayley_neumann_terms):
69
+ Q_power = torch.bmm(Q_power, Q_skew)
70
+ R.add_(Q_power, alpha=2.0)
71
+ else:
72
+ id_mat = torch.eye(self.block_size, device=Q_skew.device).unsqueeze(0).expand_as(Q_skew)
73
+ R = torch.linalg.solve(id_mat + Q_skew, id_mat - Q_skew, left=False)
74
+ return R.to(previous_dtype)
75
+
76
+ def get_rotation_matrix(self) -> torch.Tensor:
77
+ weight = self.weight
78
+ if self.coft:
79
+ with torch.no_grad():
80
+ projected_weight = self._project_batch()
81
+ weight.copy_(projected_weight)
82
+ return self._cayley_batch(weight)
83
+
84
+
85
+ class OFTv2Adapter(WeightAdapterBase):
86
+ name = "oftv2"
87
+
88
+ def __init__(self, loaded_keys: set[str], weights: tuple):
89
+ self.loaded_keys = loaded_keys
90
+ self.weights = weights
91
+
92
+ @classmethod
93
+ def load(
94
+ cls,
95
+ x: str,
96
+ lora: dict[str, torch.Tensor],
97
+ alpha: float,
98
+ dora_scale: torch.Tensor,
99
+ loaded_keys: Optional[set[str]] = None,
100
+ ) -> Optional["OFTv2Adapter"]:
101
+ if loaded_keys is None:
102
+ loaded_keys = set()
103
+ oft_r_weight_name = f"{x}.oft_R.weight"
104
+ if oft_r_weight_name in lora:
105
+ oft_r_weight = lora[oft_r_weight_name]
106
+ loaded_keys.add(oft_r_weight_name)
107
+ weights = (oft_r_weight, alpha, dora_scale)
108
+ return cls(loaded_keys, weights)
109
+ return None
110
+
111
+ def calculate_weight(
112
+ self,
113
+ weight,
114
+ key,
115
+ strength,
116
+ strength_model,
117
+ offset,
118
+ function,
119
+ intermediate_dtype=torch.float32,
120
+ original_weight=None,
121
+ ):
122
+ if strength == 0.0:
123
+ return weight
124
+
125
+ oft_r_weight_orig, alpha, dora_scale = self.weights
126
+
127
+ try:
128
+ oft_r_weight_processed = oft_r_weight_orig.to(weight.device, dtype=intermediate_dtype)
129
+
130
+ r_loaded, n_elements = oft_r_weight_processed.shape
131
+ block_size_f = (1 + (1 + 8 * n_elements) ** 0.5) / 2
132
+ if abs(block_size_f - round(block_size_f)) > 1e-6:
133
+ logging.error(f"OFTv2: Could not determine integer block_size for {key}. n_elements={n_elements} is invalid.")
134
+ return weight
135
+ block_size = int(round(block_size_f))
136
+
137
+ base_weight = original_weight if original_weight is not None else weight
138
+ out_features, *in_dims_tuple = base_weight.shape
139
+ in_features = torch.prod(torch.tensor(in_dims_tuple)).item()
140
+
141
+ if in_features % block_size != 0:
142
+ logging.warning(f"OFTv2: in_features ({in_features}) not divisible by block_size ({block_size}) for {key}.")
143
+ return weight
144
+
145
+ r_actual = in_features // block_size
146
+ block_share = r_loaded == 1
147
+
148
+ if not block_share and r_loaded != r_actual:
149
+ logging.error(f"OFTv2: Mismatch in number of blocks for {key}. Loaded: {r_loaded}, Expected: {r_actual}.")
150
+ return weight
151
+
152
+ # Pass the unscaled weight to the utility to get the full rotation matrix
153
+ util = OFTRotationUtil(oft_r_weight_processed, block_size)
154
+ orth_rotate = util.get_rotation_matrix()
155
+
156
+ # For Linear layers, rotates the input (x @ R), equivalent to rotating weights by R.T (W @ R.T).
157
+ # For Conv2d layers, rotates the weights directly (W @ R) to preserve spatial information.
158
+
159
+ # Linear delta: W @ (R.T - I)
160
+ # Conv2d delta: W @ (R - I)
161
+ I = torch.eye(block_size, device=orth_rotate.device, dtype=orth_rotate.dtype)
162
+
163
+ # Use weight dimension to determine layer type. Linear is 2D, Conv2d is 4D.
164
+ is_conv2d = base_weight.dim() == 4
165
+
166
+ if is_conv2d:
167
+ # Use R for Conv2d layers
168
+ rotation_matrix_for_weight = orth_rotate
169
+ else:
170
+ # Use R.T for Linear layers
171
+ rotation_matrix_for_weight = orth_rotate.transpose(-1, -2)
172
+
173
+ if block_share:
174
+ diff_matrix = rotation_matrix_for_weight - I.unsqueeze(0)
175
+ else:
176
+ diff_matrix = rotation_matrix_for_weight - I
177
+
178
+ w_flat = base_weight.view(out_features, in_features)
179
+ w_reshaped = w_flat.view(out_features, r_actual, block_size).to(intermediate_dtype)
180
+
181
+ if block_share:
182
+ w_diff_reshaped = torch.einsum("ork, kc -> orc", w_reshaped, diff_matrix.squeeze(0))
183
+ else:
184
+ w_diff_reshaped = torch.einsum("ork, rkc -> orc", w_reshaped, diff_matrix)
185
+
186
+ lora_diff = w_diff_reshaped.reshape(base_weight.shape)
187
+
188
+ if dora_scale is not None:
189
+ weight = weight_decompose(dora_scale, weight, lora_diff, strength, 1.0, intermediate_dtype, function)
190
+ else:
191
+ weight += function((lora_diff * strength).type(weight.dtype))
192
+
193
+ except Exception as e:
194
+ logging.error(f"ERROR applying OFTv2 for {key}: {e}", exc_info=True)
195
+
196
+ return weight
modules_forge/packages/gguf/LICENSE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2023 Georgi Gerganov
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
modules_forge/packages/gguf/README.md ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ ## Forge's implementation of GGUF
2
+ - Code is based on **llama.cpp**'s GGUF
3
+ - The main difference is that it supports PyTorch quant/dequant
modules_forge/packages/gguf/__init__.py ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ from .constants import *
2
+ from .gguf_reader import *
3
+ from .gguf_writer import *
4
+ from .lazy import *
5
+ from .metadata import *
6
+ from .quants import *
7
+ from .tensor_mapping import *
8
+ from .utility import *
modules_forge/packages/gguf/constants.py ADDED
@@ -0,0 +1,1362 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from enum import Enum, IntEnum, auto
4
+ from typing import Any
5
+
6
+ #
7
+ # constants
8
+ #
9
+
10
+ GGUF_MAGIC = 0x46554747 # "GGUF"
11
+ GGUF_VERSION = 3
12
+ GGUF_DEFAULT_ALIGNMENT = 32
13
+ GGML_QUANT_VERSION = 2 # GGML_QNT_VERSION from ggml.h
14
+
15
+ #
16
+ # metadata keys
17
+ #
18
+
19
+
20
+ class Keys:
21
+ class General:
22
+ TYPE = "general.type"
23
+ ARCHITECTURE = "general.architecture"
24
+ QUANTIZATION_VERSION = "general.quantization_version"
25
+ ALIGNMENT = "general.alignment"
26
+ FILE_TYPE = "general.file_type"
27
+
28
+ # Authorship Metadata
29
+ NAME = "general.name"
30
+ AUTHOR = "general.author"
31
+ VERSION = "general.version"
32
+ ORGANIZATION = "general.organization"
33
+
34
+ FINETUNE = "general.finetune"
35
+ BASENAME = "general.basename"
36
+
37
+ DESCRIPTION = "general.description"
38
+ QUANTIZED_BY = "general.quantized_by"
39
+
40
+ SIZE_LABEL = "general.size_label"
41
+
42
+ # Licensing details
43
+ LICENSE = "general.license"
44
+ LICENSE_NAME = "general.license.name"
45
+ LICENSE_LINK = "general.license.link"
46
+
47
+ # Typically represents the converted GGUF repo (Unless native)
48
+ URL = "general.url" # Model Website/Paper
49
+ DOI = "general.doi"
50
+ UUID = "general.uuid"
51
+ REPO_URL = "general.repo_url" # Model Source Repository (git/svn/etc...)
52
+
53
+ # Model Source during conversion
54
+ SOURCE_URL = "general.source.url" # Model Website/Paper
55
+ SOURCE_DOI = "general.source.doi"
56
+ SOURCE_UUID = "general.source.uuid"
57
+ SOURCE_REPO_URL = (
58
+ "general.source.repo_url" # Model Source Repository (git/svn/etc...)
59
+ )
60
+
61
+ # Base Model Source. There can be more than one source if it's a merged
62
+ # model like with 'Mistral-7B-Merge-14-v0.1'. This will assist in
63
+ # tracing linage of models as it is finetuned or merged over time.
64
+ BASE_MODEL_COUNT = "general.base_model.count"
65
+ BASE_MODEL_NAME = "general.base_model.{id}.name"
66
+ BASE_MODEL_AUTHOR = "general.base_model.{id}.author"
67
+ BASE_MODEL_VERSION = "general.base_model.{id}.version"
68
+ BASE_MODEL_ORGANIZATION = "general.base_model.{id}.organization"
69
+ BASE_MODEL_URL = "general.base_model.{id}.url" # Model Website/Paper
70
+ BASE_MODEL_DOI = "general.base_model.{id}.doi"
71
+ BASE_MODEL_UUID = "general.base_model.{id}.uuid"
72
+ BASE_MODEL_REPO_URL = "general.base_model.{id}.repo_url" # Model Source Repository (git/svn/etc...)
73
+
74
+ # Array based KV stores
75
+ TAGS = "general.tags"
76
+ LANGUAGES = "general.languages"
77
+ DATASETS = "general.datasets"
78
+
79
+ class LLM:
80
+ VOCAB_SIZE = "{arch}.vocab_size"
81
+ CONTEXT_LENGTH = "{arch}.context_length"
82
+ EMBEDDING_LENGTH = "{arch}.embedding_length"
83
+ BLOCK_COUNT = "{arch}.block_count"
84
+ LEADING_DENSE_BLOCK_COUNT = "{arch}.leading_dense_block_count"
85
+ FEED_FORWARD_LENGTH = "{arch}.feed_forward_length"
86
+ EXPERT_FEED_FORWARD_LENGTH = "{arch}.expert_feed_forward_length"
87
+ EXPERT_SHARED_FEED_FORWARD_LENGTH = "{arch}.expert_shared_feed_forward_length"
88
+ USE_PARALLEL_RESIDUAL = "{arch}.use_parallel_residual"
89
+ TENSOR_DATA_LAYOUT = "{arch}.tensor_data_layout"
90
+ EXPERT_COUNT = "{arch}.expert_count"
91
+ EXPERT_USED_COUNT = "{arch}.expert_used_count"
92
+ EXPERT_SHARED_COUNT = "{arch}.expert_shared_count"
93
+ EXPERT_WEIGHTS_SCALE = "{arch}.expert_weights_scale"
94
+ POOLING_TYPE = "{arch}.pooling_type"
95
+ LOGIT_SCALE = "{arch}.logit_scale"
96
+ DECODER_START_TOKEN_ID = "{arch}.decoder_start_token_id"
97
+ ATTN_LOGIT_SOFTCAPPING = "{arch}.attn_logit_softcapping"
98
+ FINAL_LOGIT_SOFTCAPPING = "{arch}.final_logit_softcapping"
99
+
100
+ class Attention:
101
+ HEAD_COUNT = "{arch}.attention.head_count"
102
+ HEAD_COUNT_KV = "{arch}.attention.head_count_kv"
103
+ MAX_ALIBI_BIAS = "{arch}.attention.max_alibi_bias"
104
+ CLAMP_KQV = "{arch}.attention.clamp_kqv"
105
+ KEY_LENGTH = "{arch}.attention.key_length"
106
+ VALUE_LENGTH = "{arch}.attention.value_length"
107
+ LAYERNORM_EPS = "{arch}.attention.layer_norm_epsilon"
108
+ LAYERNORM_RMS_EPS = "{arch}.attention.layer_norm_rms_epsilon"
109
+ CAUSAL = "{arch}.attention.causal"
110
+ Q_LORA_RANK = "{arch}.attention.q_lora_rank"
111
+ KV_LORA_RANK = "{arch}.attention.kv_lora_rank"
112
+ REL_BUCKETS_COUNT = "{arch}.attention.relative_buckets_count"
113
+ SLIDING_WINDOW = "{arch}.attention.sliding_window"
114
+
115
+ class Rope:
116
+ DIMENSION_COUNT = "{arch}.rope.dimension_count"
117
+ FREQ_BASE = "{arch}.rope.freq_base"
118
+ SCALING_TYPE = "{arch}.rope.scaling.type"
119
+ SCALING_FACTOR = "{arch}.rope.scaling.factor"
120
+ SCALING_ATTN_FACTOR = "{arch}.rope.scaling.attn_factor"
121
+ SCALING_ORIG_CTX_LEN = "{arch}.rope.scaling.original_context_length"
122
+ SCALING_FINETUNED = "{arch}.rope.scaling.finetuned"
123
+ SCALING_YARN_LOG_MUL = "{arch}.rope.scaling.yarn_log_multiplier"
124
+
125
+ class Split:
126
+ LLM_KV_SPLIT_NO = "split.no"
127
+ LLM_KV_SPLIT_COUNT = "split.count"
128
+ LLM_KV_SPLIT_TENSORS_COUNT = "split.tensors.count"
129
+
130
+ class SSM:
131
+ CONV_KERNEL = "{arch}.ssm.conv_kernel"
132
+ INNER_SIZE = "{arch}.ssm.inner_size"
133
+ STATE_SIZE = "{arch}.ssm.state_size"
134
+ TIME_STEP_RANK = "{arch}.ssm.time_step_rank"
135
+
136
+ class Tokenizer:
137
+ MODEL = "tokenizer.ggml.model"
138
+ PRE = "tokenizer.ggml.pre"
139
+ LIST = "tokenizer.ggml.tokens"
140
+ TOKEN_TYPE = "tokenizer.ggml.token_type"
141
+ TOKEN_TYPE_COUNT = (
142
+ "tokenizer.ggml.token_type_count" # for BERT-style token types
143
+ )
144
+ SCORES = "tokenizer.ggml.scores"
145
+ MERGES = "tokenizer.ggml.merges"
146
+ BOS_ID = "tokenizer.ggml.bos_token_id"
147
+ EOS_ID = "tokenizer.ggml.eos_token_id"
148
+ UNK_ID = "tokenizer.ggml.unknown_token_id"
149
+ SEP_ID = "tokenizer.ggml.seperator_token_id"
150
+ PAD_ID = "tokenizer.ggml.padding_token_id"
151
+ CLS_ID = "tokenizer.ggml.cls_token_id"
152
+ MASK_ID = "tokenizer.ggml.mask_token_id"
153
+ ADD_BOS = "tokenizer.ggml.add_bos_token"
154
+ ADD_EOS = "tokenizer.ggml.add_eos_token"
155
+ ADD_PREFIX = "tokenizer.ggml.add_space_prefix"
156
+ REMOVE_EXTRA_WS = "tokenizer.ggml.remove_extra_whitespaces"
157
+ PRECOMPILED_CHARSMAP = "tokenizer.ggml.precompiled_charsmap"
158
+ HF_JSON = "tokenizer.huggingface.json"
159
+ RWKV = "tokenizer.rwkv.world"
160
+ CHAT_TEMPLATE = "tokenizer.chat_template"
161
+ CHAT_TEMPLATE_N = "tokenizer.chat_template.{name}"
162
+ CHAT_TEMPLATES = "tokenizer.chat_templates"
163
+ # FIM/Infill special tokens constants
164
+ PREFIX_ID = "tokenizer.ggml.prefix_token_id"
165
+ SUFFIX_ID = "tokenizer.ggml.suffix_token_id"
166
+ MIDDLE_ID = "tokenizer.ggml.middle_token_id"
167
+ EOT_ID = "tokenizer.ggml.eot_token_id"
168
+ EOM_ID = "tokenizer.ggml.eom_token_id"
169
+
170
+ class Adapter:
171
+ TYPE = "adapter.type"
172
+ LORA_ALPHA = "adapter.lora.alpha"
173
+
174
+
175
+ #
176
+ # recommended mapping of model tensor names for storage in gguf
177
+ #
178
+
179
+
180
+ class GGUFType:
181
+ MODEL = "model"
182
+ ADAPTER = "adapter"
183
+
184
+
185
+ class MODEL_ARCH(IntEnum):
186
+ LLAMA = auto()
187
+ FALCON = auto()
188
+ BAICHUAN = auto()
189
+ GROK = auto()
190
+ GPT2 = auto()
191
+ GPTJ = auto()
192
+ GPTNEOX = auto()
193
+ MPT = auto()
194
+ STARCODER = auto()
195
+ REFACT = auto()
196
+ BERT = auto()
197
+ NOMIC_BERT = auto()
198
+ JINA_BERT_V2 = auto()
199
+ BLOOM = auto()
200
+ STABLELM = auto()
201
+ QWEN = auto()
202
+ QWEN2 = auto()
203
+ QWEN2MOE = auto()
204
+ PHI2 = auto()
205
+ PHI3 = auto()
206
+ PLAMO = auto()
207
+ CODESHELL = auto()
208
+ ORION = auto()
209
+ INTERNLM2 = auto()
210
+ MINICPM = auto()
211
+ GEMMA = auto()
212
+ GEMMA2 = auto()
213
+ STARCODER2 = auto()
214
+ MAMBA = auto()
215
+ XVERSE = auto()
216
+ COMMAND_R = auto()
217
+ DBRX = auto()
218
+ OLMO = auto()
219
+ OPENELM = auto()
220
+ ARCTIC = auto()
221
+ DEEPSEEK2 = auto()
222
+ CHATGLM = auto()
223
+ BITNET = auto()
224
+ T5 = auto()
225
+ T5ENCODER = auto()
226
+ JAIS = auto()
227
+
228
+
229
+ class MODEL_TENSOR(IntEnum):
230
+ TOKEN_EMBD = auto()
231
+ TOKEN_EMBD_NORM = auto()
232
+ TOKEN_TYPES = auto()
233
+ POS_EMBD = auto()
234
+ OUTPUT = auto()
235
+ OUTPUT_NORM = auto()
236
+ ROPE_FREQS = auto()
237
+ ROPE_FACTORS_LONG = auto()
238
+ ROPE_FACTORS_SHORT = auto()
239
+ ATTN_Q = auto()
240
+ ATTN_K = auto()
241
+ ATTN_V = auto()
242
+ ATTN_QKV = auto()
243
+ ATTN_OUT = auto()
244
+ ATTN_NORM = auto()
245
+ ATTN_NORM_2 = auto()
246
+ ATTN_OUT_NORM = auto()
247
+ ATTN_POST_NORM = auto()
248
+ ATTN_ROT_EMBD = auto()
249
+ FFN_GATE_INP = auto()
250
+ FFN_GATE_INP_SHEXP = auto()
251
+ FFN_NORM = auto()
252
+ FFN_PRE_NORM = auto()
253
+ FFN_POST_NORM = auto()
254
+ FFN_GATE = auto()
255
+ FFN_DOWN = auto()
256
+ FFN_UP = auto()
257
+ FFN_ACT = auto()
258
+ FFN_NORM_EXP = auto()
259
+ FFN_GATE_EXP = auto()
260
+ FFN_DOWN_EXP = auto()
261
+ FFN_UP_EXP = auto()
262
+ FFN_GATE_SHEXP = auto()
263
+ FFN_DOWN_SHEXP = auto()
264
+ FFN_UP_SHEXP = auto()
265
+ ATTN_Q_NORM = auto()
266
+ ATTN_K_NORM = auto()
267
+ LAYER_OUT_NORM = auto()
268
+ SSM_IN = auto()
269
+ SSM_CONV1D = auto()
270
+ SSM_X = auto()
271
+ SSM_DT = auto()
272
+ SSM_A = auto()
273
+ SSM_D = auto()
274
+ SSM_OUT = auto()
275
+ ATTN_Q_A = auto()
276
+ ATTN_Q_B = auto()
277
+ ATTN_KV_A_MQA = auto()
278
+ ATTN_KV_B = auto()
279
+ ATTN_Q_A_NORM = auto()
280
+ ATTN_KV_A_NORM = auto()
281
+ FFN_SUB_NORM = auto()
282
+ ATTN_SUB_NORM = auto()
283
+ DEC_ATTN_NORM = auto()
284
+ DEC_ATTN_Q = auto()
285
+ DEC_ATTN_K = auto()
286
+ DEC_ATTN_V = auto()
287
+ DEC_ATTN_OUT = auto()
288
+ DEC_ATTN_REL_B = auto()
289
+ DEC_CROSS_ATTN_NORM = auto()
290
+ DEC_CROSS_ATTN_Q = auto()
291
+ DEC_CROSS_ATTN_K = auto()
292
+ DEC_CROSS_ATTN_V = auto()
293
+ DEC_CROSS_ATTN_OUT = auto()
294
+ DEC_CROSS_ATTN_REL_B = auto()
295
+ DEC_FFN_NORM = auto()
296
+ DEC_FFN_GATE = auto()
297
+ DEC_FFN_DOWN = auto()
298
+ DEC_FFN_UP = auto()
299
+ DEC_OUTPUT_NORM = auto()
300
+ ENC_ATTN_NORM = auto()
301
+ ENC_ATTN_Q = auto()
302
+ ENC_ATTN_K = auto()
303
+ ENC_ATTN_V = auto()
304
+ ENC_ATTN_OUT = auto()
305
+ ENC_ATTN_REL_B = auto()
306
+ ENC_FFN_NORM = auto()
307
+ ENC_FFN_GATE = auto()
308
+ ENC_FFN_DOWN = auto()
309
+ ENC_FFN_UP = auto()
310
+ ENC_OUTPUT_NORM = auto()
311
+
312
+
313
+ MODEL_ARCH_NAMES: dict[MODEL_ARCH, str] = {
314
+ MODEL_ARCH.LLAMA: "llama",
315
+ MODEL_ARCH.FALCON: "falcon",
316
+ MODEL_ARCH.BAICHUAN: "baichuan",
317
+ MODEL_ARCH.GROK: "grok",
318
+ MODEL_ARCH.GPT2: "gpt2",
319
+ MODEL_ARCH.GPTJ: "gptj",
320
+ MODEL_ARCH.GPTNEOX: "gptneox",
321
+ MODEL_ARCH.MPT: "mpt",
322
+ MODEL_ARCH.STARCODER: "starcoder",
323
+ MODEL_ARCH.REFACT: "refact",
324
+ MODEL_ARCH.BERT: "bert",
325
+ MODEL_ARCH.NOMIC_BERT: "nomic-bert",
326
+ MODEL_ARCH.JINA_BERT_V2: "jina-bert-v2",
327
+ MODEL_ARCH.BLOOM: "bloom",
328
+ MODEL_ARCH.STABLELM: "stablelm",
329
+ MODEL_ARCH.QWEN: "qwen",
330
+ MODEL_ARCH.QWEN2: "qwen2",
331
+ MODEL_ARCH.QWEN2MOE: "qwen2moe",
332
+ MODEL_ARCH.PHI2: "phi2",
333
+ MODEL_ARCH.PHI3: "phi3",
334
+ MODEL_ARCH.PLAMO: "plamo",
335
+ MODEL_ARCH.CODESHELL: "codeshell",
336
+ MODEL_ARCH.ORION: "orion",
337
+ MODEL_ARCH.INTERNLM2: "internlm2",
338
+ MODEL_ARCH.MINICPM: "minicpm",
339
+ MODEL_ARCH.GEMMA: "gemma",
340
+ MODEL_ARCH.GEMMA2: "gemma2",
341
+ MODEL_ARCH.STARCODER2: "starcoder2",
342
+ MODEL_ARCH.MAMBA: "mamba",
343
+ MODEL_ARCH.XVERSE: "xverse",
344
+ MODEL_ARCH.COMMAND_R: "command-r",
345
+ MODEL_ARCH.DBRX: "dbrx",
346
+ MODEL_ARCH.OLMO: "olmo",
347
+ MODEL_ARCH.OPENELM: "openelm",
348
+ MODEL_ARCH.ARCTIC: "arctic",
349
+ MODEL_ARCH.DEEPSEEK2: "deepseek2",
350
+ MODEL_ARCH.CHATGLM: "chatglm",
351
+ MODEL_ARCH.BITNET: "bitnet",
352
+ MODEL_ARCH.T5: "t5",
353
+ MODEL_ARCH.T5ENCODER: "t5encoder",
354
+ MODEL_ARCH.JAIS: "jais",
355
+ }
356
+
357
+ TENSOR_NAMES: dict[MODEL_TENSOR, str] = {
358
+ MODEL_TENSOR.TOKEN_EMBD: "token_embd",
359
+ MODEL_TENSOR.TOKEN_EMBD_NORM: "token_embd_norm",
360
+ MODEL_TENSOR.TOKEN_TYPES: "token_types",
361
+ MODEL_TENSOR.POS_EMBD: "position_embd",
362
+ MODEL_TENSOR.OUTPUT_NORM: "output_norm",
363
+ MODEL_TENSOR.OUTPUT: "output",
364
+ MODEL_TENSOR.ROPE_FREQS: "rope_freqs",
365
+ MODEL_TENSOR.ROPE_FACTORS_LONG: "rope_factors_long",
366
+ MODEL_TENSOR.ROPE_FACTORS_SHORT: "rope_factors_short",
367
+ MODEL_TENSOR.ATTN_NORM: "blk.{bid}.attn_norm",
368
+ MODEL_TENSOR.ATTN_NORM_2: "blk.{bid}.attn_norm_2",
369
+ MODEL_TENSOR.ATTN_QKV: "blk.{bid}.attn_qkv",
370
+ MODEL_TENSOR.ATTN_Q: "blk.{bid}.attn_q",
371
+ MODEL_TENSOR.ATTN_K: "blk.{bid}.attn_k",
372
+ MODEL_TENSOR.ATTN_V: "blk.{bid}.attn_v",
373
+ MODEL_TENSOR.ATTN_OUT: "blk.{bid}.attn_output",
374
+ MODEL_TENSOR.ATTN_ROT_EMBD: "blk.{bid}.attn_rot_embd",
375
+ MODEL_TENSOR.ATTN_Q_NORM: "blk.{bid}.attn_q_norm",
376
+ MODEL_TENSOR.ATTN_K_NORM: "blk.{bid}.attn_k_norm",
377
+ MODEL_TENSOR.ATTN_OUT_NORM: "blk.{bid}.attn_output_norm",
378
+ MODEL_TENSOR.ATTN_POST_NORM: "blk.{bid}.post_attention_norm",
379
+ MODEL_TENSOR.FFN_GATE_INP: "blk.{bid}.ffn_gate_inp",
380
+ MODEL_TENSOR.FFN_GATE_INP_SHEXP: "blk.{bid}.ffn_gate_inp_shexp",
381
+ MODEL_TENSOR.FFN_NORM: "blk.{bid}.ffn_norm",
382
+ MODEL_TENSOR.FFN_PRE_NORM: "blk.{bid}.ffn_norm",
383
+ MODEL_TENSOR.FFN_POST_NORM: "blk.{bid}.post_ffw_norm",
384
+ MODEL_TENSOR.FFN_GATE: "blk.{bid}.ffn_gate",
385
+ MODEL_TENSOR.FFN_DOWN: "blk.{bid}.ffn_down",
386
+ MODEL_TENSOR.FFN_UP: "blk.{bid}.ffn_up",
387
+ MODEL_TENSOR.FFN_GATE_SHEXP: "blk.{bid}.ffn_gate_shexp",
388
+ MODEL_TENSOR.FFN_DOWN_SHEXP: "blk.{bid}.ffn_down_shexp",
389
+ MODEL_TENSOR.FFN_UP_SHEXP: "blk.{bid}.ffn_up_shexp",
390
+ MODEL_TENSOR.FFN_ACT: "blk.{bid}.ffn",
391
+ MODEL_TENSOR.FFN_NORM_EXP: "blk.{bid}.ffn_norm_exps",
392
+ MODEL_TENSOR.FFN_GATE_EXP: "blk.{bid}.ffn_gate_exps",
393
+ MODEL_TENSOR.FFN_DOWN_EXP: "blk.{bid}.ffn_down_exps",
394
+ MODEL_TENSOR.FFN_UP_EXP: "blk.{bid}.ffn_up_exps",
395
+ MODEL_TENSOR.LAYER_OUT_NORM: "blk.{bid}.layer_output_norm",
396
+ MODEL_TENSOR.SSM_IN: "blk.{bid}.ssm_in",
397
+ MODEL_TENSOR.SSM_CONV1D: "blk.{bid}.ssm_conv1d",
398
+ MODEL_TENSOR.SSM_X: "blk.{bid}.ssm_x",
399
+ MODEL_TENSOR.SSM_DT: "blk.{bid}.ssm_dt",
400
+ MODEL_TENSOR.SSM_A: "blk.{bid}.ssm_a",
401
+ MODEL_TENSOR.SSM_D: "blk.{bid}.ssm_d",
402
+ MODEL_TENSOR.SSM_OUT: "blk.{bid}.ssm_out",
403
+ MODEL_TENSOR.ATTN_Q_A: "blk.{bid}.attn_q_a",
404
+ MODEL_TENSOR.ATTN_Q_B: "blk.{bid}.attn_q_b",
405
+ MODEL_TENSOR.ATTN_KV_A_MQA: "blk.{bid}.attn_kv_a_mqa",
406
+ MODEL_TENSOR.ATTN_KV_B: "blk.{bid}.attn_kv_b",
407
+ MODEL_TENSOR.ATTN_Q_A_NORM: "blk.{bid}.attn_q_a_norm",
408
+ MODEL_TENSOR.ATTN_KV_A_NORM: "blk.{bid}.attn_kv_a_norm",
409
+ MODEL_TENSOR.ATTN_SUB_NORM: "blk.{bid}.attn_sub_norm",
410
+ MODEL_TENSOR.FFN_SUB_NORM: "blk.{bid}.ffn_sub_norm",
411
+ MODEL_TENSOR.DEC_ATTN_NORM: "dec.blk.{bid}.attn_norm",
412
+ MODEL_TENSOR.DEC_ATTN_Q: "dec.blk.{bid}.attn_q",
413
+ MODEL_TENSOR.DEC_ATTN_K: "dec.blk.{bid}.attn_k",
414
+ MODEL_TENSOR.DEC_ATTN_V: "dec.blk.{bid}.attn_v",
415
+ MODEL_TENSOR.DEC_ATTN_OUT: "dec.blk.{bid}.attn_o",
416
+ MODEL_TENSOR.DEC_ATTN_REL_B: "dec.blk.{bid}.attn_rel_b",
417
+ MODEL_TENSOR.DEC_CROSS_ATTN_NORM: "dec.blk.{bid}.cross_attn_norm",
418
+ MODEL_TENSOR.DEC_CROSS_ATTN_Q: "dec.blk.{bid}.cross_attn_q",
419
+ MODEL_TENSOR.DEC_CROSS_ATTN_K: "dec.blk.{bid}.cross_attn_k",
420
+ MODEL_TENSOR.DEC_CROSS_ATTN_V: "dec.blk.{bid}.cross_attn_v",
421
+ MODEL_TENSOR.DEC_CROSS_ATTN_OUT: "dec.blk.{bid}.cross_attn_o",
422
+ MODEL_TENSOR.DEC_CROSS_ATTN_REL_B: "dec.blk.{bid}.cross_attn_rel_b",
423
+ MODEL_TENSOR.DEC_FFN_NORM: "dec.blk.{bid}.ffn_norm",
424
+ MODEL_TENSOR.DEC_FFN_GATE: "dec.blk.{bid}.ffn_gate",
425
+ MODEL_TENSOR.DEC_FFN_DOWN: "dec.blk.{bid}.ffn_down",
426
+ MODEL_TENSOR.DEC_FFN_UP: "dec.blk.{bid}.ffn_up",
427
+ MODEL_TENSOR.DEC_OUTPUT_NORM: "dec.output_norm",
428
+ MODEL_TENSOR.ENC_ATTN_NORM: "enc.blk.{bid}.attn_norm",
429
+ MODEL_TENSOR.ENC_ATTN_Q: "enc.blk.{bid}.attn_q",
430
+ MODEL_TENSOR.ENC_ATTN_K: "enc.blk.{bid}.attn_k",
431
+ MODEL_TENSOR.ENC_ATTN_V: "enc.blk.{bid}.attn_v",
432
+ MODEL_TENSOR.ENC_ATTN_OUT: "enc.blk.{bid}.attn_o",
433
+ MODEL_TENSOR.ENC_ATTN_REL_B: "enc.blk.{bid}.attn_rel_b",
434
+ MODEL_TENSOR.ENC_FFN_NORM: "enc.blk.{bid}.ffn_norm",
435
+ MODEL_TENSOR.ENC_FFN_GATE: "enc.blk.{bid}.ffn_gate",
436
+ MODEL_TENSOR.ENC_FFN_DOWN: "enc.blk.{bid}.ffn_down",
437
+ MODEL_TENSOR.ENC_FFN_UP: "enc.blk.{bid}.ffn_up",
438
+ MODEL_TENSOR.ENC_OUTPUT_NORM: "enc.output_norm",
439
+ }
440
+
441
+ MODEL_TENSORS: dict[MODEL_ARCH, list[MODEL_TENSOR]] = {
442
+ MODEL_ARCH.LLAMA: [
443
+ MODEL_TENSOR.TOKEN_EMBD,
444
+ MODEL_TENSOR.OUTPUT_NORM,
445
+ MODEL_TENSOR.OUTPUT,
446
+ MODEL_TENSOR.ROPE_FREQS,
447
+ MODEL_TENSOR.ATTN_NORM,
448
+ MODEL_TENSOR.ATTN_Q,
449
+ MODEL_TENSOR.ATTN_K,
450
+ MODEL_TENSOR.ATTN_V,
451
+ MODEL_TENSOR.ATTN_OUT,
452
+ MODEL_TENSOR.ATTN_ROT_EMBD,
453
+ MODEL_TENSOR.FFN_GATE_INP,
454
+ MODEL_TENSOR.FFN_NORM,
455
+ MODEL_TENSOR.FFN_GATE,
456
+ MODEL_TENSOR.FFN_DOWN,
457
+ MODEL_TENSOR.FFN_UP,
458
+ MODEL_TENSOR.FFN_GATE_EXP,
459
+ MODEL_TENSOR.FFN_DOWN_EXP,
460
+ MODEL_TENSOR.FFN_UP_EXP,
461
+ ],
462
+ MODEL_ARCH.GROK: [
463
+ MODEL_TENSOR.TOKEN_EMBD,
464
+ MODEL_TENSOR.OUTPUT_NORM,
465
+ MODEL_TENSOR.OUTPUT,
466
+ MODEL_TENSOR.ROPE_FREQS,
467
+ MODEL_TENSOR.ATTN_NORM,
468
+ MODEL_TENSOR.ATTN_Q,
469
+ MODEL_TENSOR.ATTN_K,
470
+ MODEL_TENSOR.ATTN_V,
471
+ MODEL_TENSOR.ATTN_OUT,
472
+ MODEL_TENSOR.ATTN_ROT_EMBD,
473
+ MODEL_TENSOR.ATTN_OUT_NORM,
474
+ MODEL_TENSOR.FFN_GATE_INP,
475
+ MODEL_TENSOR.FFN_NORM,
476
+ MODEL_TENSOR.FFN_GATE,
477
+ MODEL_TENSOR.FFN_DOWN,
478
+ MODEL_TENSOR.FFN_UP,
479
+ MODEL_TENSOR.FFN_GATE_EXP,
480
+ MODEL_TENSOR.FFN_DOWN_EXP,
481
+ MODEL_TENSOR.FFN_UP_EXP,
482
+ MODEL_TENSOR.LAYER_OUT_NORM,
483
+ ],
484
+ MODEL_ARCH.GPTNEOX: [
485
+ MODEL_TENSOR.TOKEN_EMBD,
486
+ MODEL_TENSOR.OUTPUT_NORM,
487
+ MODEL_TENSOR.OUTPUT,
488
+ MODEL_TENSOR.ATTN_NORM,
489
+ MODEL_TENSOR.ATTN_QKV,
490
+ MODEL_TENSOR.ATTN_OUT,
491
+ MODEL_TENSOR.FFN_NORM,
492
+ MODEL_TENSOR.FFN_DOWN,
493
+ MODEL_TENSOR.FFN_UP,
494
+ ],
495
+ MODEL_ARCH.FALCON: [
496
+ MODEL_TENSOR.TOKEN_EMBD,
497
+ MODEL_TENSOR.OUTPUT_NORM,
498
+ MODEL_TENSOR.OUTPUT,
499
+ MODEL_TENSOR.ATTN_NORM,
500
+ MODEL_TENSOR.ATTN_NORM_2,
501
+ MODEL_TENSOR.ATTN_QKV,
502
+ MODEL_TENSOR.ATTN_OUT,
503
+ MODEL_TENSOR.FFN_DOWN,
504
+ MODEL_TENSOR.FFN_UP,
505
+ ],
506
+ MODEL_ARCH.BAICHUAN: [
507
+ MODEL_TENSOR.TOKEN_EMBD,
508
+ MODEL_TENSOR.OUTPUT_NORM,
509
+ MODEL_TENSOR.OUTPUT,
510
+ MODEL_TENSOR.ROPE_FREQS,
511
+ MODEL_TENSOR.ATTN_NORM,
512
+ MODEL_TENSOR.ATTN_Q,
513
+ MODEL_TENSOR.ATTN_K,
514
+ MODEL_TENSOR.ATTN_V,
515
+ MODEL_TENSOR.ATTN_OUT,
516
+ MODEL_TENSOR.ATTN_ROT_EMBD,
517
+ MODEL_TENSOR.FFN_NORM,
518
+ MODEL_TENSOR.FFN_GATE,
519
+ MODEL_TENSOR.FFN_DOWN,
520
+ MODEL_TENSOR.FFN_UP,
521
+ ],
522
+ MODEL_ARCH.STARCODER: [
523
+ MODEL_TENSOR.TOKEN_EMBD,
524
+ MODEL_TENSOR.POS_EMBD,
525
+ MODEL_TENSOR.OUTPUT_NORM,
526
+ MODEL_TENSOR.OUTPUT,
527
+ MODEL_TENSOR.ATTN_NORM,
528
+ MODEL_TENSOR.ATTN_QKV,
529
+ MODEL_TENSOR.ATTN_OUT,
530
+ MODEL_TENSOR.FFN_NORM,
531
+ MODEL_TENSOR.FFN_DOWN,
532
+ MODEL_TENSOR.FFN_UP,
533
+ ],
534
+ MODEL_ARCH.BERT: [
535
+ MODEL_TENSOR.TOKEN_EMBD,
536
+ MODEL_TENSOR.TOKEN_EMBD_NORM,
537
+ MODEL_TENSOR.TOKEN_TYPES,
538
+ MODEL_TENSOR.POS_EMBD,
539
+ MODEL_TENSOR.OUTPUT_NORM,
540
+ MODEL_TENSOR.ATTN_OUT_NORM,
541
+ MODEL_TENSOR.ATTN_Q,
542
+ MODEL_TENSOR.ATTN_K,
543
+ MODEL_TENSOR.ATTN_V,
544
+ MODEL_TENSOR.ATTN_OUT,
545
+ MODEL_TENSOR.FFN_DOWN,
546
+ MODEL_TENSOR.FFN_UP,
547
+ MODEL_TENSOR.LAYER_OUT_NORM,
548
+ ],
549
+ MODEL_ARCH.NOMIC_BERT: [
550
+ MODEL_TENSOR.TOKEN_EMBD,
551
+ MODEL_TENSOR.TOKEN_EMBD_NORM,
552
+ MODEL_TENSOR.TOKEN_TYPES,
553
+ MODEL_TENSOR.POS_EMBD,
554
+ MODEL_TENSOR.OUTPUT_NORM,
555
+ MODEL_TENSOR.ATTN_OUT_NORM,
556
+ MODEL_TENSOR.ATTN_QKV,
557
+ MODEL_TENSOR.ATTN_OUT,
558
+ MODEL_TENSOR.FFN_GATE,
559
+ MODEL_TENSOR.FFN_DOWN,
560
+ MODEL_TENSOR.FFN_UP,
561
+ MODEL_TENSOR.LAYER_OUT_NORM,
562
+ ],
563
+ MODEL_ARCH.JINA_BERT_V2: [
564
+ MODEL_TENSOR.TOKEN_EMBD,
565
+ MODEL_TENSOR.TOKEN_EMBD_NORM,
566
+ MODEL_TENSOR.TOKEN_TYPES,
567
+ MODEL_TENSOR.ATTN_NORM_2,
568
+ MODEL_TENSOR.ATTN_OUT_NORM,
569
+ MODEL_TENSOR.ATTN_Q,
570
+ MODEL_TENSOR.ATTN_Q_NORM,
571
+ MODEL_TENSOR.ATTN_K,
572
+ MODEL_TENSOR.ATTN_K_NORM,
573
+ MODEL_TENSOR.ATTN_V,
574
+ MODEL_TENSOR.ATTN_OUT,
575
+ MODEL_TENSOR.FFN_UP,
576
+ MODEL_TENSOR.FFN_GATE,
577
+ MODEL_TENSOR.FFN_DOWN,
578
+ MODEL_TENSOR.LAYER_OUT_NORM,
579
+ ],
580
+ MODEL_ARCH.MPT: [
581
+ MODEL_TENSOR.TOKEN_EMBD,
582
+ MODEL_TENSOR.OUTPUT_NORM,
583
+ MODEL_TENSOR.OUTPUT,
584
+ MODEL_TENSOR.ATTN_NORM,
585
+ MODEL_TENSOR.ATTN_QKV,
586
+ MODEL_TENSOR.ATTN_OUT,
587
+ MODEL_TENSOR.FFN_NORM,
588
+ MODEL_TENSOR.FFN_DOWN,
589
+ MODEL_TENSOR.FFN_UP,
590
+ MODEL_TENSOR.FFN_ACT,
591
+ MODEL_TENSOR.ATTN_Q_NORM,
592
+ MODEL_TENSOR.ATTN_K_NORM,
593
+ MODEL_TENSOR.POS_EMBD,
594
+ ],
595
+ MODEL_ARCH.GPTJ: [
596
+ MODEL_TENSOR.TOKEN_EMBD,
597
+ MODEL_TENSOR.OUTPUT_NORM,
598
+ MODEL_TENSOR.OUTPUT,
599
+ MODEL_TENSOR.ATTN_NORM,
600
+ MODEL_TENSOR.ATTN_Q,
601
+ MODEL_TENSOR.ATTN_K,
602
+ MODEL_TENSOR.ATTN_V,
603
+ MODEL_TENSOR.ATTN_OUT,
604
+ MODEL_TENSOR.FFN_DOWN,
605
+ MODEL_TENSOR.FFN_UP,
606
+ ],
607
+ MODEL_ARCH.REFACT: [
608
+ MODEL_TENSOR.TOKEN_EMBD,
609
+ MODEL_TENSOR.OUTPUT_NORM,
610
+ MODEL_TENSOR.OUTPUT,
611
+ MODEL_TENSOR.ATTN_NORM,
612
+ MODEL_TENSOR.ATTN_Q,
613
+ MODEL_TENSOR.ATTN_K,
614
+ MODEL_TENSOR.ATTN_V,
615
+ MODEL_TENSOR.ATTN_OUT,
616
+ MODEL_TENSOR.FFN_NORM,
617
+ MODEL_TENSOR.FFN_GATE,
618
+ MODEL_TENSOR.FFN_DOWN,
619
+ MODEL_TENSOR.FFN_UP,
620
+ ],
621
+ MODEL_ARCH.BLOOM: [
622
+ MODEL_TENSOR.TOKEN_EMBD,
623
+ MODEL_TENSOR.TOKEN_EMBD_NORM,
624
+ MODEL_TENSOR.OUTPUT_NORM,
625
+ MODEL_TENSOR.OUTPUT,
626
+ MODEL_TENSOR.ATTN_NORM,
627
+ MODEL_TENSOR.ATTN_QKV,
628
+ MODEL_TENSOR.ATTN_OUT,
629
+ MODEL_TENSOR.FFN_NORM,
630
+ MODEL_TENSOR.FFN_DOWN,
631
+ MODEL_TENSOR.FFN_UP,
632
+ ],
633
+ MODEL_ARCH.STABLELM: [
634
+ MODEL_TENSOR.TOKEN_EMBD,
635
+ MODEL_TENSOR.OUTPUT_NORM,
636
+ MODEL_TENSOR.OUTPUT,
637
+ MODEL_TENSOR.ROPE_FREQS,
638
+ MODEL_TENSOR.ATTN_NORM,
639
+ MODEL_TENSOR.ATTN_Q,
640
+ MODEL_TENSOR.ATTN_K,
641
+ MODEL_TENSOR.ATTN_V,
642
+ MODEL_TENSOR.ATTN_OUT,
643
+ MODEL_TENSOR.FFN_NORM,
644
+ MODEL_TENSOR.FFN_GATE,
645
+ MODEL_TENSOR.FFN_DOWN,
646
+ MODEL_TENSOR.FFN_UP,
647
+ MODEL_TENSOR.ATTN_Q_NORM,
648
+ MODEL_TENSOR.ATTN_K_NORM,
649
+ ],
650
+ MODEL_ARCH.QWEN: [
651
+ MODEL_TENSOR.TOKEN_EMBD,
652
+ MODEL_TENSOR.OUTPUT_NORM,
653
+ MODEL_TENSOR.OUTPUT,
654
+ MODEL_TENSOR.ROPE_FREQS,
655
+ MODEL_TENSOR.ATTN_NORM,
656
+ MODEL_TENSOR.ATTN_QKV,
657
+ MODEL_TENSOR.ATTN_OUT,
658
+ MODEL_TENSOR.ATTN_ROT_EMBD,
659
+ MODEL_TENSOR.FFN_NORM,
660
+ MODEL_TENSOR.FFN_GATE,
661
+ MODEL_TENSOR.FFN_DOWN,
662
+ MODEL_TENSOR.FFN_UP,
663
+ ],
664
+ MODEL_ARCH.QWEN2: [
665
+ MODEL_TENSOR.TOKEN_EMBD,
666
+ MODEL_TENSOR.OUTPUT_NORM,
667
+ MODEL_TENSOR.OUTPUT,
668
+ MODEL_TENSOR.ATTN_NORM,
669
+ MODEL_TENSOR.ATTN_Q,
670
+ MODEL_TENSOR.ATTN_K,
671
+ MODEL_TENSOR.ATTN_V,
672
+ MODEL_TENSOR.ATTN_OUT,
673
+ MODEL_TENSOR.FFN_NORM,
674
+ MODEL_TENSOR.FFN_GATE,
675
+ MODEL_TENSOR.FFN_DOWN,
676
+ MODEL_TENSOR.FFN_UP,
677
+ ],
678
+ MODEL_ARCH.QWEN2MOE: [
679
+ MODEL_TENSOR.TOKEN_EMBD,
680
+ MODEL_TENSOR.OUTPUT_NORM,
681
+ MODEL_TENSOR.OUTPUT,
682
+ MODEL_TENSOR.ATTN_NORM,
683
+ MODEL_TENSOR.ATTN_Q,
684
+ MODEL_TENSOR.ATTN_K,
685
+ MODEL_TENSOR.ATTN_V,
686
+ MODEL_TENSOR.ATTN_OUT,
687
+ MODEL_TENSOR.FFN_NORM,
688
+ MODEL_TENSOR.FFN_GATE_INP,
689
+ MODEL_TENSOR.FFN_GATE_EXP,
690
+ MODEL_TENSOR.FFN_DOWN_EXP,
691
+ MODEL_TENSOR.FFN_UP_EXP,
692
+ MODEL_TENSOR.FFN_GATE_INP_SHEXP,
693
+ MODEL_TENSOR.FFN_GATE_SHEXP,
694
+ MODEL_TENSOR.FFN_DOWN_SHEXP,
695
+ MODEL_TENSOR.FFN_UP_SHEXP,
696
+ ],
697
+ MODEL_ARCH.PLAMO: [
698
+ MODEL_TENSOR.TOKEN_EMBD,
699
+ MODEL_TENSOR.OUTPUT_NORM,
700
+ MODEL_TENSOR.OUTPUT,
701
+ MODEL_TENSOR.ROPE_FREQS,
702
+ MODEL_TENSOR.ATTN_NORM,
703
+ MODEL_TENSOR.ATTN_Q,
704
+ MODEL_TENSOR.ATTN_K,
705
+ MODEL_TENSOR.ATTN_V,
706
+ MODEL_TENSOR.ATTN_OUT,
707
+ MODEL_TENSOR.ATTN_ROT_EMBD,
708
+ MODEL_TENSOR.FFN_GATE,
709
+ MODEL_TENSOR.FFN_DOWN,
710
+ MODEL_TENSOR.FFN_UP,
711
+ ],
712
+ MODEL_ARCH.GPT2: [
713
+ MODEL_TENSOR.TOKEN_EMBD,
714
+ MODEL_TENSOR.POS_EMBD,
715
+ MODEL_TENSOR.OUTPUT_NORM,
716
+ MODEL_TENSOR.OUTPUT,
717
+ MODEL_TENSOR.ATTN_NORM,
718
+ MODEL_TENSOR.ATTN_QKV,
719
+ MODEL_TENSOR.ATTN_OUT,
720
+ MODEL_TENSOR.FFN_NORM,
721
+ MODEL_TENSOR.FFN_DOWN,
722
+ MODEL_TENSOR.FFN_UP,
723
+ ],
724
+ MODEL_ARCH.PHI2: [
725
+ MODEL_TENSOR.TOKEN_EMBD,
726
+ MODEL_TENSOR.OUTPUT_NORM,
727
+ MODEL_TENSOR.OUTPUT,
728
+ MODEL_TENSOR.ATTN_NORM,
729
+ MODEL_TENSOR.ATTN_QKV,
730
+ MODEL_TENSOR.ATTN_Q,
731
+ MODEL_TENSOR.ATTN_K,
732
+ MODEL_TENSOR.ATTN_V,
733
+ MODEL_TENSOR.ATTN_OUT,
734
+ MODEL_TENSOR.FFN_NORM,
735
+ MODEL_TENSOR.FFN_DOWN,
736
+ MODEL_TENSOR.FFN_UP,
737
+ ],
738
+ MODEL_ARCH.PHI3: [
739
+ MODEL_TENSOR.TOKEN_EMBD,
740
+ MODEL_TENSOR.OUTPUT_NORM,
741
+ MODEL_TENSOR.OUTPUT,
742
+ MODEL_TENSOR.ATTN_NORM,
743
+ MODEL_TENSOR.ATTN_QKV,
744
+ MODEL_TENSOR.ATTN_Q,
745
+ MODEL_TENSOR.ATTN_K,
746
+ MODEL_TENSOR.ATTN_V,
747
+ MODEL_TENSOR.ATTN_OUT,
748
+ MODEL_TENSOR.FFN_NORM,
749
+ MODEL_TENSOR.FFN_DOWN,
750
+ MODEL_TENSOR.FFN_UP,
751
+ ],
752
+ MODEL_ARCH.CODESHELL: [
753
+ MODEL_TENSOR.TOKEN_EMBD,
754
+ MODEL_TENSOR.POS_EMBD,
755
+ MODEL_TENSOR.OUTPUT_NORM,
756
+ MODEL_TENSOR.OUTPUT,
757
+ MODEL_TENSOR.ATTN_NORM,
758
+ MODEL_TENSOR.ATTN_QKV,
759
+ MODEL_TENSOR.ATTN_OUT,
760
+ MODEL_TENSOR.ATTN_ROT_EMBD,
761
+ MODEL_TENSOR.FFN_NORM,
762
+ MODEL_TENSOR.FFN_DOWN,
763
+ MODEL_TENSOR.FFN_UP,
764
+ ],
765
+ MODEL_ARCH.ORION: [
766
+ MODEL_TENSOR.TOKEN_EMBD,
767
+ MODEL_TENSOR.OUTPUT_NORM,
768
+ MODEL_TENSOR.OUTPUT,
769
+ MODEL_TENSOR.ROPE_FREQS,
770
+ MODEL_TENSOR.ATTN_NORM,
771
+ MODEL_TENSOR.ATTN_Q,
772
+ MODEL_TENSOR.ATTN_K,
773
+ MODEL_TENSOR.ATTN_V,
774
+ MODEL_TENSOR.ATTN_OUT,
775
+ MODEL_TENSOR.ATTN_ROT_EMBD,
776
+ MODEL_TENSOR.FFN_NORM,
777
+ MODEL_TENSOR.FFN_GATE,
778
+ MODEL_TENSOR.FFN_DOWN,
779
+ MODEL_TENSOR.FFN_UP,
780
+ ],
781
+ MODEL_ARCH.INTERNLM2: [
782
+ MODEL_TENSOR.TOKEN_EMBD,
783
+ MODEL_TENSOR.OUTPUT_NORM,
784
+ MODEL_TENSOR.OUTPUT,
785
+ MODEL_TENSOR.ATTN_NORM,
786
+ MODEL_TENSOR.ATTN_Q,
787
+ MODEL_TENSOR.ATTN_K,
788
+ MODEL_TENSOR.ATTN_V,
789
+ MODEL_TENSOR.ATTN_OUT,
790
+ MODEL_TENSOR.ATTN_ROT_EMBD,
791
+ MODEL_TENSOR.FFN_NORM,
792
+ MODEL_TENSOR.FFN_GATE,
793
+ MODEL_TENSOR.FFN_DOWN,
794
+ MODEL_TENSOR.FFN_UP,
795
+ ],
796
+ MODEL_ARCH.MINICPM: [
797
+ MODEL_TENSOR.TOKEN_EMBD,
798
+ MODEL_TENSOR.OUTPUT,
799
+ MODEL_TENSOR.OUTPUT_NORM,
800
+ MODEL_TENSOR.ROPE_FREQS,
801
+ MODEL_TENSOR.ATTN_NORM,
802
+ MODEL_TENSOR.ATTN_Q,
803
+ MODEL_TENSOR.ATTN_K,
804
+ MODEL_TENSOR.ATTN_V,
805
+ MODEL_TENSOR.ATTN_OUT,
806
+ MODEL_TENSOR.ATTN_ROT_EMBD,
807
+ MODEL_TENSOR.FFN_GATE_INP,
808
+ MODEL_TENSOR.FFN_NORM,
809
+ MODEL_TENSOR.FFN_GATE,
810
+ MODEL_TENSOR.FFN_DOWN,
811
+ MODEL_TENSOR.FFN_UP,
812
+ MODEL_TENSOR.FFN_GATE_EXP,
813
+ MODEL_TENSOR.FFN_DOWN_EXP,
814
+ MODEL_TENSOR.FFN_UP_EXP,
815
+ ],
816
+ MODEL_ARCH.GEMMA: [
817
+ MODEL_TENSOR.TOKEN_EMBD,
818
+ MODEL_TENSOR.OUTPUT_NORM,
819
+ MODEL_TENSOR.ATTN_NORM,
820
+ MODEL_TENSOR.ATTN_Q,
821
+ MODEL_TENSOR.ATTN_K,
822
+ MODEL_TENSOR.ATTN_V,
823
+ MODEL_TENSOR.ATTN_OUT,
824
+ MODEL_TENSOR.FFN_GATE,
825
+ MODEL_TENSOR.FFN_DOWN,
826
+ MODEL_TENSOR.FFN_UP,
827
+ MODEL_TENSOR.FFN_NORM,
828
+ ],
829
+ MODEL_ARCH.GEMMA2: [
830
+ MODEL_TENSOR.TOKEN_EMBD,
831
+ MODEL_TENSOR.OUTPUT_NORM,
832
+ MODEL_TENSOR.ATTN_Q,
833
+ MODEL_TENSOR.ATTN_K,
834
+ MODEL_TENSOR.ATTN_V,
835
+ MODEL_TENSOR.ATTN_OUT,
836
+ MODEL_TENSOR.FFN_GATE,
837
+ MODEL_TENSOR.FFN_DOWN,
838
+ MODEL_TENSOR.FFN_UP,
839
+ MODEL_TENSOR.ATTN_NORM,
840
+ MODEL_TENSOR.ATTN_POST_NORM,
841
+ MODEL_TENSOR.FFN_PRE_NORM,
842
+ MODEL_TENSOR.FFN_POST_NORM,
843
+ ],
844
+ MODEL_ARCH.STARCODER2: [
845
+ MODEL_TENSOR.TOKEN_EMBD,
846
+ MODEL_TENSOR.OUTPUT_NORM,
847
+ MODEL_TENSOR.OUTPUT,
848
+ MODEL_TENSOR.ROPE_FREQS,
849
+ MODEL_TENSOR.ATTN_NORM,
850
+ MODEL_TENSOR.ATTN_Q,
851
+ MODEL_TENSOR.ATTN_K,
852
+ MODEL_TENSOR.ATTN_V,
853
+ MODEL_TENSOR.ATTN_OUT,
854
+ MODEL_TENSOR.ATTN_ROT_EMBD,
855
+ MODEL_TENSOR.FFN_NORM,
856
+ MODEL_TENSOR.FFN_DOWN,
857
+ MODEL_TENSOR.FFN_UP,
858
+ ],
859
+ MODEL_ARCH.MAMBA: [
860
+ MODEL_TENSOR.TOKEN_EMBD,
861
+ MODEL_TENSOR.OUTPUT_NORM,
862
+ MODEL_TENSOR.OUTPUT,
863
+ MODEL_TENSOR.ATTN_NORM,
864
+ MODEL_TENSOR.SSM_IN,
865
+ MODEL_TENSOR.SSM_CONV1D,
866
+ MODEL_TENSOR.SSM_X,
867
+ MODEL_TENSOR.SSM_DT,
868
+ MODEL_TENSOR.SSM_A,
869
+ MODEL_TENSOR.SSM_D,
870
+ MODEL_TENSOR.SSM_OUT,
871
+ ],
872
+ MODEL_ARCH.XVERSE: [
873
+ MODEL_TENSOR.TOKEN_EMBD,
874
+ MODEL_TENSOR.OUTPUT_NORM,
875
+ MODEL_TENSOR.OUTPUT,
876
+ MODEL_TENSOR.ROPE_FREQS,
877
+ MODEL_TENSOR.ATTN_NORM,
878
+ MODEL_TENSOR.ATTN_Q,
879
+ MODEL_TENSOR.ATTN_K,
880
+ MODEL_TENSOR.ATTN_V,
881
+ MODEL_TENSOR.ATTN_OUT,
882
+ MODEL_TENSOR.ATTN_ROT_EMBD,
883
+ MODEL_TENSOR.FFN_NORM,
884
+ MODEL_TENSOR.FFN_GATE,
885
+ MODEL_TENSOR.FFN_DOWN,
886
+ MODEL_TENSOR.FFN_UP,
887
+ ],
888
+ MODEL_ARCH.COMMAND_R: [
889
+ MODEL_TENSOR.TOKEN_EMBD,
890
+ MODEL_TENSOR.OUTPUT_NORM,
891
+ MODEL_TENSOR.ATTN_NORM,
892
+ MODEL_TENSOR.ATTN_Q,
893
+ MODEL_TENSOR.ATTN_K,
894
+ MODEL_TENSOR.ATTN_V,
895
+ MODEL_TENSOR.ATTN_OUT,
896
+ MODEL_TENSOR.FFN_GATE,
897
+ MODEL_TENSOR.FFN_DOWN,
898
+ MODEL_TENSOR.FFN_UP,
899
+ MODEL_TENSOR.ATTN_K_NORM,
900
+ MODEL_TENSOR.ATTN_Q_NORM,
901
+ ],
902
+ MODEL_ARCH.DBRX: [
903
+ MODEL_TENSOR.TOKEN_EMBD,
904
+ MODEL_TENSOR.OUTPUT_NORM,
905
+ MODEL_TENSOR.OUTPUT,
906
+ MODEL_TENSOR.ATTN_NORM,
907
+ MODEL_TENSOR.ATTN_QKV,
908
+ MODEL_TENSOR.ATTN_OUT,
909
+ MODEL_TENSOR.ATTN_OUT_NORM,
910
+ MODEL_TENSOR.FFN_GATE_INP,
911
+ MODEL_TENSOR.FFN_GATE_EXP,
912
+ MODEL_TENSOR.FFN_DOWN_EXP,
913
+ MODEL_TENSOR.FFN_UP_EXP,
914
+ ],
915
+ MODEL_ARCH.OLMO: [
916
+ MODEL_TENSOR.TOKEN_EMBD,
917
+ MODEL_TENSOR.OUTPUT,
918
+ MODEL_TENSOR.ATTN_Q,
919
+ MODEL_TENSOR.ATTN_K,
920
+ MODEL_TENSOR.ATTN_V,
921
+ MODEL_TENSOR.ATTN_OUT,
922
+ MODEL_TENSOR.FFN_GATE,
923
+ MODEL_TENSOR.FFN_DOWN,
924
+ MODEL_TENSOR.FFN_UP,
925
+ ],
926
+ MODEL_ARCH.OPENELM: [
927
+ MODEL_TENSOR.TOKEN_EMBD,
928
+ MODEL_TENSOR.OUTPUT_NORM,
929
+ MODEL_TENSOR.ATTN_NORM,
930
+ MODEL_TENSOR.ATTN_QKV,
931
+ MODEL_TENSOR.ATTN_Q_NORM,
932
+ MODEL_TENSOR.ATTN_K_NORM,
933
+ MODEL_TENSOR.ATTN_OUT,
934
+ MODEL_TENSOR.FFN_NORM,
935
+ MODEL_TENSOR.FFN_GATE,
936
+ MODEL_TENSOR.FFN_DOWN,
937
+ MODEL_TENSOR.FFN_UP,
938
+ ],
939
+ MODEL_ARCH.ARCTIC: [
940
+ MODEL_TENSOR.TOKEN_EMBD,
941
+ MODEL_TENSOR.OUTPUT_NORM,
942
+ MODEL_TENSOR.OUTPUT,
943
+ MODEL_TENSOR.ROPE_FREQS,
944
+ MODEL_TENSOR.ATTN_NORM,
945
+ MODEL_TENSOR.ATTN_Q,
946
+ MODEL_TENSOR.ATTN_K,
947
+ MODEL_TENSOR.ATTN_V,
948
+ MODEL_TENSOR.ATTN_OUT,
949
+ MODEL_TENSOR.ATTN_ROT_EMBD,
950
+ MODEL_TENSOR.FFN_GATE_INP,
951
+ MODEL_TENSOR.FFN_NORM,
952
+ MODEL_TENSOR.FFN_GATE,
953
+ MODEL_TENSOR.FFN_DOWN,
954
+ MODEL_TENSOR.FFN_UP,
955
+ MODEL_TENSOR.FFN_NORM_EXP,
956
+ MODEL_TENSOR.FFN_GATE_EXP,
957
+ MODEL_TENSOR.FFN_DOWN_EXP,
958
+ MODEL_TENSOR.FFN_UP_EXP,
959
+ ],
960
+ MODEL_ARCH.DEEPSEEK2: [
961
+ MODEL_TENSOR.TOKEN_EMBD,
962
+ MODEL_TENSOR.OUTPUT_NORM,
963
+ MODEL_TENSOR.OUTPUT,
964
+ MODEL_TENSOR.ROPE_FREQS,
965
+ MODEL_TENSOR.ATTN_NORM,
966
+ MODEL_TENSOR.ATTN_Q,
967
+ MODEL_TENSOR.ATTN_Q_A,
968
+ MODEL_TENSOR.ATTN_Q_B,
969
+ MODEL_TENSOR.ATTN_KV_A_MQA,
970
+ MODEL_TENSOR.ATTN_KV_B,
971
+ MODEL_TENSOR.ATTN_Q_A_NORM,
972
+ MODEL_TENSOR.ATTN_KV_A_NORM,
973
+ MODEL_TENSOR.ATTN_OUT,
974
+ MODEL_TENSOR.ATTN_ROT_EMBD,
975
+ MODEL_TENSOR.FFN_GATE_INP,
976
+ MODEL_TENSOR.FFN_NORM,
977
+ MODEL_TENSOR.FFN_GATE,
978
+ MODEL_TENSOR.FFN_DOWN,
979
+ MODEL_TENSOR.FFN_UP,
980
+ MODEL_TENSOR.FFN_GATE_EXP,
981
+ MODEL_TENSOR.FFN_DOWN_EXP,
982
+ MODEL_TENSOR.FFN_UP_EXP,
983
+ MODEL_TENSOR.FFN_GATE_SHEXP,
984
+ MODEL_TENSOR.FFN_DOWN_SHEXP,
985
+ MODEL_TENSOR.FFN_UP_SHEXP,
986
+ ],
987
+ MODEL_ARCH.CHATGLM: [
988
+ MODEL_TENSOR.TOKEN_EMBD,
989
+ MODEL_TENSOR.ROPE_FREQS,
990
+ MODEL_TENSOR.OUTPUT_NORM,
991
+ MODEL_TENSOR.OUTPUT,
992
+ MODEL_TENSOR.ATTN_NORM,
993
+ MODEL_TENSOR.ATTN_QKV,
994
+ MODEL_TENSOR.ATTN_OUT,
995
+ MODEL_TENSOR.FFN_NORM,
996
+ MODEL_TENSOR.FFN_DOWN,
997
+ MODEL_TENSOR.FFN_UP,
998
+ ],
999
+ MODEL_ARCH.BITNET: [
1000
+ MODEL_TENSOR.ATTN_Q,
1001
+ MODEL_TENSOR.ATTN_K,
1002
+ MODEL_TENSOR.ATTN_V,
1003
+ MODEL_TENSOR.TOKEN_EMBD,
1004
+ MODEL_TENSOR.OUTPUT_NORM,
1005
+ MODEL_TENSOR.ATTN_NORM,
1006
+ MODEL_TENSOR.ATTN_OUT,
1007
+ MODEL_TENSOR.FFN_NORM,
1008
+ MODEL_TENSOR.FFN_GATE,
1009
+ MODEL_TENSOR.FFN_DOWN,
1010
+ MODEL_TENSOR.FFN_UP,
1011
+ MODEL_TENSOR.ATTN_SUB_NORM,
1012
+ MODEL_TENSOR.FFN_SUB_NORM,
1013
+ ],
1014
+ MODEL_ARCH.T5: [
1015
+ MODEL_TENSOR.TOKEN_EMBD,
1016
+ MODEL_TENSOR.OUTPUT,
1017
+ MODEL_TENSOR.DEC_ATTN_NORM,
1018
+ MODEL_TENSOR.DEC_ATTN_Q,
1019
+ MODEL_TENSOR.DEC_ATTN_K,
1020
+ MODEL_TENSOR.DEC_ATTN_V,
1021
+ MODEL_TENSOR.DEC_ATTN_OUT,
1022
+ MODEL_TENSOR.DEC_ATTN_REL_B,
1023
+ MODEL_TENSOR.DEC_CROSS_ATTN_NORM,
1024
+ MODEL_TENSOR.DEC_CROSS_ATTN_Q,
1025
+ MODEL_TENSOR.DEC_CROSS_ATTN_K,
1026
+ MODEL_TENSOR.DEC_CROSS_ATTN_V,
1027
+ MODEL_TENSOR.DEC_CROSS_ATTN_OUT,
1028
+ MODEL_TENSOR.DEC_CROSS_ATTN_REL_B,
1029
+ MODEL_TENSOR.DEC_FFN_NORM,
1030
+ MODEL_TENSOR.DEC_FFN_GATE,
1031
+ MODEL_TENSOR.DEC_FFN_DOWN,
1032
+ MODEL_TENSOR.DEC_FFN_UP,
1033
+ MODEL_TENSOR.DEC_OUTPUT_NORM,
1034
+ MODEL_TENSOR.ENC_ATTN_NORM,
1035
+ MODEL_TENSOR.ENC_ATTN_Q,
1036
+ MODEL_TENSOR.ENC_ATTN_K,
1037
+ MODEL_TENSOR.ENC_ATTN_V,
1038
+ MODEL_TENSOR.ENC_ATTN_OUT,
1039
+ MODEL_TENSOR.ENC_ATTN_REL_B,
1040
+ MODEL_TENSOR.ENC_FFN_NORM,
1041
+ MODEL_TENSOR.ENC_FFN_GATE,
1042
+ MODEL_TENSOR.ENC_FFN_DOWN,
1043
+ MODEL_TENSOR.ENC_FFN_UP,
1044
+ MODEL_TENSOR.ENC_OUTPUT_NORM,
1045
+ ],
1046
+ MODEL_ARCH.T5ENCODER: [
1047
+ MODEL_TENSOR.TOKEN_EMBD,
1048
+ MODEL_TENSOR.OUTPUT,
1049
+ MODEL_TENSOR.ENC_ATTN_NORM,
1050
+ MODEL_TENSOR.ENC_ATTN_Q,
1051
+ MODEL_TENSOR.ENC_ATTN_K,
1052
+ MODEL_TENSOR.ENC_ATTN_V,
1053
+ MODEL_TENSOR.ENC_ATTN_OUT,
1054
+ MODEL_TENSOR.ENC_ATTN_REL_B,
1055
+ MODEL_TENSOR.ENC_FFN_NORM,
1056
+ MODEL_TENSOR.ENC_FFN_GATE,
1057
+ MODEL_TENSOR.ENC_FFN_DOWN,
1058
+ MODEL_TENSOR.ENC_FFN_UP,
1059
+ MODEL_TENSOR.ENC_OUTPUT_NORM,
1060
+ ],
1061
+ MODEL_ARCH.JAIS: [
1062
+ MODEL_TENSOR.TOKEN_EMBD,
1063
+ MODEL_TENSOR.OUTPUT_NORM,
1064
+ MODEL_TENSOR.OUTPUT,
1065
+ MODEL_TENSOR.ATTN_NORM,
1066
+ MODEL_TENSOR.ATTN_QKV,
1067
+ MODEL_TENSOR.ATTN_OUT,
1068
+ MODEL_TENSOR.FFN_NORM,
1069
+ MODEL_TENSOR.FFN_DOWN,
1070
+ MODEL_TENSOR.FFN_GATE,
1071
+ MODEL_TENSOR.FFN_UP,
1072
+ ],
1073
+ # TODO
1074
+ }
1075
+
1076
+ # tensors that will not be serialized
1077
+ MODEL_TENSOR_SKIP: dict[MODEL_ARCH, list[MODEL_TENSOR]] = {
1078
+ MODEL_ARCH.LLAMA: [
1079
+ MODEL_TENSOR.ROPE_FREQS,
1080
+ MODEL_TENSOR.ATTN_ROT_EMBD,
1081
+ ],
1082
+ MODEL_ARCH.BAICHUAN: [
1083
+ MODEL_TENSOR.ROPE_FREQS,
1084
+ MODEL_TENSOR.ATTN_ROT_EMBD,
1085
+ ],
1086
+ MODEL_ARCH.QWEN: [
1087
+ MODEL_TENSOR.ROPE_FREQS,
1088
+ MODEL_TENSOR.ATTN_ROT_EMBD,
1089
+ ],
1090
+ MODEL_ARCH.CODESHELL: [
1091
+ MODEL_TENSOR.ROPE_FREQS,
1092
+ MODEL_TENSOR.ATTN_ROT_EMBD,
1093
+ ],
1094
+ MODEL_ARCH.ORION: [
1095
+ MODEL_TENSOR.ROPE_FREQS,
1096
+ MODEL_TENSOR.ATTN_ROT_EMBD,
1097
+ ],
1098
+ MODEL_ARCH.STARCODER2: [
1099
+ MODEL_TENSOR.ROPE_FREQS,
1100
+ MODEL_TENSOR.ATTN_ROT_EMBD,
1101
+ ],
1102
+ MODEL_ARCH.XVERSE: [
1103
+ MODEL_TENSOR.ROPE_FREQS,
1104
+ MODEL_TENSOR.ATTN_ROT_EMBD,
1105
+ ],
1106
+ MODEL_ARCH.DEEPSEEK2: [
1107
+ MODEL_TENSOR.ROPE_FREQS,
1108
+ MODEL_TENSOR.ATTN_ROT_EMBD,
1109
+ ],
1110
+ MODEL_ARCH.CHATGLM: [
1111
+ MODEL_TENSOR.ROPE_FREQS,
1112
+ ],
1113
+ }
1114
+
1115
+ #
1116
+ # types
1117
+ #
1118
+
1119
+
1120
+ class TokenType(IntEnum):
1121
+ NORMAL = 1
1122
+ UNKNOWN = 2
1123
+ CONTROL = 3
1124
+ USER_DEFINED = 4
1125
+ UNUSED = 5
1126
+ BYTE = 6
1127
+
1128
+
1129
+ class RopeScalingType(Enum):
1130
+ NONE = "none"
1131
+ LINEAR = "linear"
1132
+ YARN = "yarn"
1133
+
1134
+
1135
+ class PoolingType(IntEnum):
1136
+ NONE = 0
1137
+ MEAN = 1
1138
+ CLS = 2
1139
+
1140
+
1141
+ class GGMLQuantizationType(IntEnum):
1142
+ F32 = 0
1143
+ F16 = 1
1144
+ Q4_0 = 2
1145
+ Q4_1 = 3
1146
+ Q5_0 = 6
1147
+ Q5_1 = 7
1148
+ Q8_0 = 8
1149
+ Q8_1 = 9
1150
+ Q2_K = 10
1151
+ Q3_K = 11
1152
+ Q4_K = 12
1153
+ Q5_K = 13
1154
+ Q6_K = 14
1155
+ Q8_K = 15
1156
+ IQ2_XXS = 16
1157
+ IQ2_XS = 17
1158
+ IQ3_XXS = 18
1159
+ IQ1_S = 19
1160
+ IQ4_NL = 20
1161
+ IQ3_S = 21
1162
+ IQ2_S = 22
1163
+ IQ4_XS = 23
1164
+ I8 = 24
1165
+ I16 = 25
1166
+ I32 = 26
1167
+ I64 = 27
1168
+ F64 = 28
1169
+ IQ1_M = 29
1170
+ BF16 = 30
1171
+ Q4_0_4_4 = 31
1172
+ Q4_0_4_8 = 32
1173
+ Q4_0_8_8 = 33
1174
+
1175
+
1176
+ # TODO: add GGMLFileType from ggml_ftype in ggml.h
1177
+
1178
+
1179
+ # from llama_ftype in llama.h
1180
+ # ALL VALUES SHOULD BE THE SAME HERE AS THEY ARE OVER THERE.
1181
+ class LlamaFileType(IntEnum):
1182
+ ALL_F32 = 0
1183
+ MOSTLY_F16 = 1 # except 1d tensors
1184
+ MOSTLY_Q4_0 = 2 # except 1d tensors
1185
+ MOSTLY_Q4_1 = 3 # except 1d tensors
1186
+ # MOSTLY_Q4_1_SOME_F16 = 4 # tok_embeddings.weight and output.weight are F16
1187
+ # MOSTLY_Q4_2 = 5 # support has been removed
1188
+ # MOSTLY_Q4_3 = 6 # support has been removed
1189
+ MOSTLY_Q8_0 = 7 # except 1d tensors
1190
+ MOSTLY_Q5_0 = 8 # except 1d tensors
1191
+ MOSTLY_Q5_1 = 9 # except 1d tensors
1192
+ MOSTLY_Q2_K = 10 # except 1d tensors
1193
+ MOSTLY_Q3_K_S = 11 # except 1d tensors
1194
+ MOSTLY_Q3_K_M = 12 # except 1d tensors
1195
+ MOSTLY_Q3_K_L = 13 # except 1d tensors
1196
+ MOSTLY_Q4_K_S = 14 # except 1d tensors
1197
+ MOSTLY_Q4_K_M = 15 # except 1d tensors
1198
+ MOSTLY_Q5_K_S = 16 # except 1d tensors
1199
+ MOSTLY_Q5_K_M = 17 # except 1d tensors
1200
+ MOSTLY_Q6_K = 18 # except 1d tensors
1201
+ MOSTLY_IQ2_XXS = 19 # except 1d tensors
1202
+ MOSTLY_IQ2_XS = 20 # except 1d tensors
1203
+ MOSTLY_Q2_K_S = 21 # except 1d tensors
1204
+ MOSTLY_IQ3_XS = 22 # except 1d tensors
1205
+ MOSTLY_IQ3_XXS = 23 # except 1d tensors
1206
+ MOSTLY_IQ1_S = 24 # except 1d tensors
1207
+ MOSTLY_IQ4_NL = 25 # except 1d tensors
1208
+ MOSTLY_IQ3_S = 26 # except 1d tensors
1209
+ MOSTLY_IQ3_M = 27 # except 1d tensors
1210
+ MOSTLY_IQ2_S = 28 # except 1d tensors
1211
+ MOSTLY_IQ2_M = 29 # except 1d tensors
1212
+ MOSTLY_IQ4_XS = 30 # except 1d tensors
1213
+ MOSTLY_IQ1_M = 31 # except 1d tensors
1214
+ MOSTLY_BF16 = 32 # except 1d tensors
1215
+ MOSTLY_Q4_0_4_4 = 33 # except 1d tensors
1216
+ MOSTLY_Q4_0_4_8 = 34 # except 1d tensors
1217
+ MOSTLY_Q4_0_8_8 = 35 # except 1d tensors
1218
+
1219
+ GUESSED = 1024 # not specified in the model file
1220
+
1221
+
1222
+ class GGUFEndian(IntEnum):
1223
+ LITTLE = 0
1224
+ BIG = 1
1225
+
1226
+
1227
+ class GGUFValueType(IntEnum):
1228
+ UINT8 = 0
1229
+ INT8 = 1
1230
+ UINT16 = 2
1231
+ INT16 = 3
1232
+ UINT32 = 4
1233
+ INT32 = 5
1234
+ FLOAT32 = 6
1235
+ BOOL = 7
1236
+ STRING = 8
1237
+ ARRAY = 9
1238
+ UINT64 = 10
1239
+ INT64 = 11
1240
+ FLOAT64 = 12
1241
+
1242
+ @staticmethod
1243
+ def get_type(val: Any) -> GGUFValueType:
1244
+ if isinstance(val, (str, bytes, bytearray)):
1245
+ return GGUFValueType.STRING
1246
+ elif isinstance(val, list):
1247
+ return GGUFValueType.ARRAY
1248
+ elif isinstance(val, float):
1249
+ return GGUFValueType.FLOAT32
1250
+ elif isinstance(val, bool):
1251
+ return GGUFValueType.BOOL
1252
+ elif isinstance(val, int):
1253
+ return GGUFValueType.INT32
1254
+ # TODO: need help with 64-bit types in Python
1255
+ else:
1256
+ raise ValueError(f"Unknown type: {type(val)}")
1257
+
1258
+
1259
+ # Items here are (block size, type size)
1260
+ QK_K = 256
1261
+ GGML_QUANT_SIZES: dict[GGMLQuantizationType, tuple[int, int]] = {
1262
+ GGMLQuantizationType.F32: (1, 4),
1263
+ GGMLQuantizationType.F16: (1, 2),
1264
+ GGMLQuantizationType.Q4_0: (32, 2 + 16),
1265
+ GGMLQuantizationType.Q4_1: (32, 2 + 2 + 16),
1266
+ GGMLQuantizationType.Q5_0: (32, 2 + 4 + 16),
1267
+ GGMLQuantizationType.Q5_1: (32, 2 + 2 + 4 + 16),
1268
+ GGMLQuantizationType.Q8_0: (32, 2 + 32),
1269
+ GGMLQuantizationType.Q8_1: (32, 4 + 4 + 32),
1270
+ GGMLQuantizationType.Q2_K: (256, 2 + 2 + QK_K // 16 + QK_K // 4),
1271
+ GGMLQuantizationType.Q3_K: (256, 2 + QK_K // 4 + QK_K // 8 + 12),
1272
+ GGMLQuantizationType.Q4_K: (256, 2 + 2 + QK_K // 2 + 12),
1273
+ GGMLQuantizationType.Q5_K: (256, 2 + 2 + QK_K // 2 + QK_K // 8 + 12),
1274
+ GGMLQuantizationType.Q6_K: (256, 2 + QK_K // 2 + QK_K // 4 + QK_K // 16),
1275
+ GGMLQuantizationType.Q8_K: (256, 4 + QK_K + QK_K // 8),
1276
+ GGMLQuantizationType.IQ2_XXS: (256, 2 + QK_K // 4),
1277
+ GGMLQuantizationType.IQ2_XS: (256, 2 + QK_K // 4 + QK_K // 32),
1278
+ GGMLQuantizationType.IQ3_XXS: (256, 2 + QK_K // 4 + QK_K // 8),
1279
+ GGMLQuantizationType.IQ1_S: (256, 2 + QK_K // 8 + QK_K // 16),
1280
+ GGMLQuantizationType.IQ4_NL: (32, 2 + 16),
1281
+ GGMLQuantizationType.IQ3_S: (256, 2 + QK_K // 4 + QK_K // 8 + QK_K // 32 + 4),
1282
+ GGMLQuantizationType.IQ2_S: (256, 2 + QK_K // 4 + QK_K // 16),
1283
+ GGMLQuantizationType.IQ4_XS: (256, 2 + 2 + QK_K // 2 + QK_K // 64),
1284
+ GGMLQuantizationType.I8: (1, 1),
1285
+ GGMLQuantizationType.I16: (1, 2),
1286
+ GGMLQuantizationType.I32: (1, 4),
1287
+ GGMLQuantizationType.I64: (1, 8),
1288
+ GGMLQuantizationType.F64: (1, 8),
1289
+ GGMLQuantizationType.IQ1_M: (256, QK_K // 8 + QK_K // 16 + QK_K // 32),
1290
+ GGMLQuantizationType.BF16: (1, 2),
1291
+ GGMLQuantizationType.Q4_0_4_4: (32, 2 + 16),
1292
+ GGMLQuantizationType.Q4_0_4_8: (32, 2 + 16),
1293
+ GGMLQuantizationType.Q4_0_8_8: (32, 2 + 16),
1294
+ }
1295
+
1296
+
1297
+ # Aliases for backward compatibility.
1298
+
1299
+ # general
1300
+ KEY_GENERAL_ARCHITECTURE = Keys.General.ARCHITECTURE
1301
+ KEY_GENERAL_QUANTIZATION_VERSION = Keys.General.QUANTIZATION_VERSION
1302
+ KEY_GENERAL_ALIGNMENT = Keys.General.ALIGNMENT
1303
+ KEY_GENERAL_NAME = Keys.General.NAME
1304
+ KEY_GENERAL_AUTHOR = Keys.General.AUTHOR
1305
+ KEY_GENERAL_URL = Keys.General.URL
1306
+ KEY_GENERAL_DESCRIPTION = Keys.General.DESCRIPTION
1307
+ KEY_GENERAL_LICENSE = Keys.General.LICENSE
1308
+ KEY_GENERAL_SOURCE_URL = Keys.General.SOURCE_URL
1309
+ KEY_GENERAL_FILE_TYPE = Keys.General.FILE_TYPE
1310
+
1311
+ # LLM
1312
+ KEY_VOCAB_SIZE = Keys.LLM.VOCAB_SIZE
1313
+ KEY_CONTEXT_LENGTH = Keys.LLM.CONTEXT_LENGTH
1314
+ KEY_EMBEDDING_LENGTH = Keys.LLM.EMBEDDING_LENGTH
1315
+ KEY_BLOCK_COUNT = Keys.LLM.BLOCK_COUNT
1316
+ KEY_FEED_FORWARD_LENGTH = Keys.LLM.FEED_FORWARD_LENGTH
1317
+ KEY_USE_PARALLEL_RESIDUAL = Keys.LLM.USE_PARALLEL_RESIDUAL
1318
+ KEY_TENSOR_DATA_LAYOUT = Keys.LLM.TENSOR_DATA_LAYOUT
1319
+
1320
+ # attention
1321
+ KEY_ATTENTION_HEAD_COUNT = Keys.Attention.HEAD_COUNT
1322
+ KEY_ATTENTION_HEAD_COUNT_KV = Keys.Attention.HEAD_COUNT_KV
1323
+ KEY_ATTENTION_MAX_ALIBI_BIAS = Keys.Attention.MAX_ALIBI_BIAS
1324
+ KEY_ATTENTION_CLAMP_KQV = Keys.Attention.CLAMP_KQV
1325
+ KEY_ATTENTION_LAYERNORM_EPS = Keys.Attention.LAYERNORM_EPS
1326
+ KEY_ATTENTION_LAYERNORM_RMS_EPS = Keys.Attention.LAYERNORM_RMS_EPS
1327
+
1328
+ # RoPE
1329
+ KEY_ROPE_DIMENSION_COUNT = Keys.Rope.DIMENSION_COUNT
1330
+ KEY_ROPE_FREQ_BASE = Keys.Rope.FREQ_BASE
1331
+ KEY_ROPE_SCALING_TYPE = Keys.Rope.SCALING_TYPE
1332
+ KEY_ROPE_SCALING_FACTOR = Keys.Rope.SCALING_FACTOR
1333
+ KEY_ROPE_SCALING_ORIG_CTX_LEN = Keys.Rope.SCALING_ORIG_CTX_LEN
1334
+ KEY_ROPE_SCALING_FINETUNED = Keys.Rope.SCALING_FINETUNED
1335
+
1336
+ # SSM
1337
+ KEY_SSM_CONV_KERNEL = Keys.SSM.CONV_KERNEL
1338
+ KEY_SSM_INNER_SIZE = Keys.SSM.INNER_SIZE
1339
+ KEY_SSM_STATE_SIZE = Keys.SSM.STATE_SIZE
1340
+ KEY_SSM_TIME_STEP_RANK = Keys.SSM.TIME_STEP_RANK
1341
+
1342
+ # tokenization
1343
+ KEY_TOKENIZER_MODEL = Keys.Tokenizer.MODEL
1344
+ KEY_TOKENIZER_PRE = Keys.Tokenizer.PRE
1345
+ KEY_TOKENIZER_LIST = Keys.Tokenizer.LIST
1346
+ KEY_TOKENIZER_TOKEN_TYPE = Keys.Tokenizer.TOKEN_TYPE
1347
+ KEY_TOKENIZER_SCORES = Keys.Tokenizer.SCORES
1348
+ KEY_TOKENIZER_MERGES = Keys.Tokenizer.MERGES
1349
+ KEY_TOKENIZER_BOS_ID = Keys.Tokenizer.BOS_ID
1350
+ KEY_TOKENIZER_EOS_ID = Keys.Tokenizer.EOS_ID
1351
+ KEY_TOKENIZER_UNK_ID = Keys.Tokenizer.UNK_ID
1352
+ KEY_TOKENIZER_SEP_ID = Keys.Tokenizer.SEP_ID
1353
+ KEY_TOKENIZER_PAD_ID = Keys.Tokenizer.PAD_ID
1354
+ KEY_TOKENIZER_CLS_ID = Keys.Tokenizer.CLS_ID
1355
+ KEY_TOKENIZER_MASK_ID = Keys.Tokenizer.MASK_ID
1356
+ KEY_TOKENIZER_HF_JSON = Keys.Tokenizer.HF_JSON
1357
+ KEY_TOKENIZER_RWKV = Keys.Tokenizer.RWKV
1358
+ KEY_TOKENIZER_PRIFIX_ID = Keys.Tokenizer.PREFIX_ID
1359
+ KEY_TOKENIZER_SUFFIX_ID = Keys.Tokenizer.SUFFIX_ID
1360
+ KEY_TOKENIZER_MIDDLE_ID = Keys.Tokenizer.MIDDLE_ID
1361
+ KEY_TOKENIZER_EOT_ID = Keys.Tokenizer.EOT_ID
1362
+ KEY_TOKENIZER_EOM_ID = Keys.Tokenizer.EOM_ID
modules_forge/packages/gguf/gguf_reader.py ADDED
@@ -0,0 +1,333 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # GGUF file reading/modification support. For API usage information,
3
+ # please see the files scripts/ for some fairly simple examples.
4
+ #
5
+ from __future__ import annotations
6
+
7
+ import logging
8
+ import os
9
+ from collections import OrderedDict
10
+ from typing import Any, Literal, NamedTuple, TypeVar, Union
11
+
12
+ import numpy as np
13
+ import numpy.typing as npt
14
+
15
+ from .quants import quant_shape_to_byte_shape
16
+
17
+ if __name__ == "__main__":
18
+ import sys
19
+ from pathlib import Path
20
+
21
+ # Allow running file in package as a script.
22
+ sys.path.insert(0, str(Path(__file__).parent.parent))
23
+
24
+ from gguf.constants import (
25
+ GGML_QUANT_SIZES,
26
+ GGUF_DEFAULT_ALIGNMENT,
27
+ GGUF_MAGIC,
28
+ GGUF_VERSION,
29
+ GGMLQuantizationType,
30
+ GGUFValueType,
31
+ )
32
+
33
+ logger = logging.getLogger(__name__)
34
+
35
+ READER_SUPPORTED_VERSIONS = [2, GGUF_VERSION]
36
+
37
+
38
+ class ReaderField(NamedTuple):
39
+ # Offset to start of this field.
40
+ offset: int
41
+
42
+ # Name of the field (not necessarily from file data).
43
+ name: str
44
+
45
+ # Data parts. Some types have multiple components, such as strings
46
+ # that consist of a length followed by the string data.
47
+ parts: list[npt.NDArray[Any]] = []
48
+
49
+ # Indexes into parts that we can call the actual data. For example
50
+ # an array of strings will be populated with indexes to the actual
51
+ # string data.
52
+ data: list[int] = [-1]
53
+
54
+ types: list[GGUFValueType] = []
55
+
56
+
57
+ class ReaderTensor(NamedTuple):
58
+ name: str
59
+ tensor_type: GGMLQuantizationType
60
+ shape: npt.NDArray[np.uint32]
61
+ n_elements: int
62
+ n_bytes: int
63
+ data_offset: int
64
+ data: npt.NDArray[Any]
65
+ field: ReaderField
66
+
67
+
68
+ class GGUFReader:
69
+ # I - same as host, S - swapped
70
+ byte_order: Literal["I", "S"] = "I"
71
+ alignment: int = GGUF_DEFAULT_ALIGNMENT
72
+ data_offset: int
73
+
74
+ # Note: Internal helper, API may change.
75
+ gguf_scalar_to_np: dict[GGUFValueType, type[np.generic]] = {
76
+ GGUFValueType.UINT8: np.uint8,
77
+ GGUFValueType.INT8: np.int8,
78
+ GGUFValueType.UINT16: np.uint16,
79
+ GGUFValueType.INT16: np.int16,
80
+ GGUFValueType.UINT32: np.uint32,
81
+ GGUFValueType.INT32: np.int32,
82
+ GGUFValueType.FLOAT32: np.float32,
83
+ GGUFValueType.UINT64: np.uint64,
84
+ GGUFValueType.INT64: np.int64,
85
+ GGUFValueType.FLOAT64: np.float64,
86
+ GGUFValueType.BOOL: np.bool_,
87
+ }
88
+
89
+ def __init__(self, path: os.PathLike[str] | str, mode: Literal["r", "r+", "c"] = "r"):
90
+ self.data = np.memmap(path, mode=mode)
91
+ offs = 0
92
+
93
+ # Check for GGUF magic
94
+ if self._get(offs, np.uint32, override_order="<")[0] != GGUF_MAGIC:
95
+ raise ValueError("GGUF magic invalid")
96
+ offs += 4
97
+
98
+ # Check GGUF version
99
+ temp_version = self._get(offs, np.uint32)
100
+ if temp_version[0] & 65535 == 0:
101
+ # If we get 0 here that means it's (probably) a GGUF file created for
102
+ # the opposite byte order of the machine this script is running on.
103
+ self.byte_order = "S"
104
+ temp_version = temp_version.newbyteorder(self.byte_order)
105
+ version = temp_version[0]
106
+ if version not in READER_SUPPORTED_VERSIONS:
107
+ raise ValueError(f"Sorry, file appears to be version {version} which we cannot handle")
108
+ self.fields: OrderedDict[str, ReaderField] = OrderedDict()
109
+ self.tensors: list[ReaderTensor] = []
110
+ offs += self._push_field(ReaderField(offs, "GGUF.version", [temp_version], [0], [GGUFValueType.UINT32]))
111
+
112
+ # Check tensor count and kv count
113
+ temp_counts = self._get(offs, np.uint64, 2)
114
+ offs += self._push_field(
115
+ ReaderField(
116
+ offs,
117
+ "GGUF.tensor_count",
118
+ [temp_counts[:1]],
119
+ [0],
120
+ [GGUFValueType.UINT64],
121
+ )
122
+ )
123
+ offs += self._push_field(ReaderField(offs, "GGUF.kv_count", [temp_counts[1:]], [0], [GGUFValueType.UINT64]))
124
+ tensor_count, kv_count = temp_counts
125
+ offs = self._build_fields(offs, kv_count)
126
+
127
+ # Build Tensor Info Fields
128
+ offs, tensors_fields = self._build_tensor_info(offs, tensor_count)
129
+ new_align = self.fields.get("general.alignment")
130
+ if new_align is not None:
131
+ if new_align.types != [GGUFValueType.UINT32]:
132
+ raise ValueError("Bad type for general.alignment field")
133
+ self.alignment = new_align.parts[-1][0]
134
+ padding = offs % self.alignment
135
+ if padding != 0:
136
+ offs += self.alignment - padding
137
+ self.data_offset = offs
138
+ self._build_tensors(offs, tensors_fields)
139
+
140
+ _DT = TypeVar("_DT", bound=npt.DTypeLike)
141
+
142
+ # Fetch a key/value metadata field by key.
143
+ def get_field(self, key: str) -> Union[ReaderField, None]:
144
+ return self.fields.get(key, None)
145
+
146
+ # Fetch a tensor from the list by index.
147
+ def get_tensor(self, idx: int) -> ReaderTensor:
148
+ return self.tensors[idx]
149
+
150
+ def _get(
151
+ self,
152
+ offset: int,
153
+ dtype: npt.DTypeLike,
154
+ count: int = 1,
155
+ override_order: None | Literal["I", "S", "<"] = None,
156
+ ) -> npt.NDArray[Any]:
157
+ count = int(count)
158
+ itemsize = int(np.empty([], dtype=dtype).itemsize)
159
+ end_offs = offset + itemsize * count
160
+ arr: npt.NDArray[Any] = self.data[offset:end_offs].view(dtype=dtype)[:count]
161
+ return arr.view(arr.dtype.newbyteorder(override_order or self.byte_order))
162
+
163
+ def _push_field(self, field: ReaderField, skip_sum: bool = False) -> int:
164
+ if field.name in self.fields:
165
+ # TODO: add option to generate error on duplicate keys
166
+ # raise KeyError(f'Duplicate {field.name} already in list at offset {field.offset}')
167
+
168
+ logger.warning(f"Duplicate key {field.name} at offset {field.offset}")
169
+ self.fields[field.name + "_{}".format(field.offset)] = field
170
+ else:
171
+ self.fields[field.name] = field
172
+ return 0 if skip_sum else sum(int(part.nbytes) for part in field.parts)
173
+
174
+ def _get_str(self, offset: int) -> tuple[npt.NDArray[np.uint64], npt.NDArray[np.uint8]]:
175
+ slen = self._get(offset, np.uint64)
176
+ return slen, self._get(offset + 8, np.uint8, slen[0])
177
+
178
+ def _get_field_parts(
179
+ self,
180
+ orig_offs: int,
181
+ raw_type: int,
182
+ ) -> tuple[int, list[npt.NDArray[Any]], list[int], list[GGUFValueType]]:
183
+ offs = orig_offs
184
+ types: list[GGUFValueType] = []
185
+ gtype = GGUFValueType(raw_type)
186
+ types.append(gtype)
187
+ # Handle strings.
188
+ if gtype == GGUFValueType.STRING:
189
+ sparts: list[npt.NDArray[Any]] = list(self._get_str(offs))
190
+ size = sum(int(part.nbytes) for part in sparts)
191
+ return size, sparts, [1], types
192
+ # Check if it's a simple scalar type.
193
+ nptype = self.gguf_scalar_to_np.get(gtype)
194
+ if nptype is not None:
195
+ val = self._get(offs, nptype)
196
+ return int(val.nbytes), [val], [0], types
197
+ # Handle arrays.
198
+ if gtype == GGUFValueType.ARRAY:
199
+ raw_itype = self._get(offs, np.uint32)
200
+ offs += int(raw_itype.nbytes)
201
+ alen = self._get(offs, np.uint64)
202
+ offs += int(alen.nbytes)
203
+ aparts: list[npt.NDArray[Any]] = [raw_itype, alen]
204
+ data_idxs: list[int] = []
205
+ for idx in range(alen[0]):
206
+ curr_size, curr_parts, curr_idxs, curr_types = self._get_field_parts(offs, raw_itype[0])
207
+ if idx == 0:
208
+ types += curr_types
209
+ idxs_offs = len(aparts)
210
+ aparts += curr_parts
211
+ data_idxs += (idx + idxs_offs for idx in curr_idxs)
212
+ offs += curr_size
213
+ return offs - orig_offs, aparts, data_idxs, types
214
+ # We can't deal with this one.
215
+ raise ValueError("Unknown/unhandled field type {gtype}")
216
+
217
+ def _get_tensor_info_field(self, orig_offs: int) -> ReaderField:
218
+ offs = orig_offs
219
+
220
+ # Get Tensor Name
221
+ name_len, name_data = self._get_str(offs)
222
+ offs += int(name_len.nbytes + name_data.nbytes)
223
+
224
+ # Get Tensor Dimensions Count
225
+ n_dims = self._get(offs, np.uint32)
226
+ offs += int(n_dims.nbytes)
227
+
228
+ # Get Tensor Dimension Array
229
+ dims = self._get(offs, np.uint64, n_dims[0])
230
+ offs += int(dims.nbytes)
231
+
232
+ # Get Tensor Encoding Scheme Type
233
+ raw_dtype = self._get(offs, np.uint32)
234
+ offs += int(raw_dtype.nbytes)
235
+
236
+ # Get Tensor Offset
237
+ offset_tensor = self._get(offs, np.uint64)
238
+ offs += int(offset_tensor.nbytes)
239
+
240
+ return ReaderField(
241
+ orig_offs,
242
+ str(bytes(name_data), encoding="utf-8"),
243
+ [name_len, name_data, n_dims, dims, raw_dtype, offset_tensor],
244
+ [1, 3, 4, 5],
245
+ )
246
+
247
+ def _build_fields(self, offs: int, count: int) -> int:
248
+ for _ in range(count):
249
+ orig_offs = offs
250
+ kv_klen, kv_kdata = self._get_str(offs)
251
+ offs += int(kv_klen.nbytes + kv_kdata.nbytes)
252
+ raw_kv_type = self._get(offs, np.uint32)
253
+ offs += int(raw_kv_type.nbytes)
254
+ parts: list[npt.NDArray[Any]] = [kv_klen, kv_kdata, raw_kv_type]
255
+ idxs_offs = len(parts)
256
+ field_size, field_parts, field_idxs, field_types = self._get_field_parts(offs, raw_kv_type[0])
257
+ parts += field_parts
258
+ self._push_field(
259
+ ReaderField(
260
+ orig_offs,
261
+ str(bytes(kv_kdata), encoding="utf-8"),
262
+ parts,
263
+ [idx + idxs_offs for idx in field_idxs],
264
+ field_types,
265
+ ),
266
+ skip_sum=True,
267
+ )
268
+ offs += field_size
269
+ return offs
270
+
271
+ def _build_tensor_info(self, offs: int, count: int) -> tuple[int, list[ReaderField]]:
272
+ tensor_fields = []
273
+ for _ in range(count):
274
+ field = self._get_tensor_info_field(offs)
275
+ offs += sum(int(part.nbytes) for part in field.parts)
276
+ tensor_fields.append(field)
277
+ return offs, tensor_fields
278
+
279
+ def _build_tensors(self, start_offs: int, fields: list[ReaderField]) -> None:
280
+ tensors = []
281
+ tensor_names = set() # keep track of name to prevent duplicated tensors
282
+ for field in fields:
283
+ _name_len, name_data, _n_dims, dims, raw_dtype, offset_tensor = field.parts
284
+ # check if there's any tensor having same name already in the list
285
+ tensor_name = str(bytes(name_data), encoding="utf-8")
286
+ if tensor_name in tensor_names:
287
+ raise ValueError(f"Found duplicated tensor with name {tensor_name}")
288
+ tensor_names.add(tensor_name)
289
+ ggml_type = GGMLQuantizationType(raw_dtype[0])
290
+ n_elems = int(np.prod(dims))
291
+ np_dims = tuple(reversed(dims.tolist()))
292
+ block_size, type_size = GGML_QUANT_SIZES[ggml_type]
293
+ n_bytes = n_elems * type_size // block_size
294
+ data_offs = int(start_offs + offset_tensor[0])
295
+ item_type: npt.DTypeLike
296
+ if ggml_type == GGMLQuantizationType.F16:
297
+ item_count = n_elems
298
+ item_type = np.float16
299
+ elif ggml_type == GGMLQuantizationType.F32:
300
+ item_count = n_elems
301
+ item_type = np.float32
302
+ elif ggml_type == GGMLQuantizationType.F64:
303
+ item_count = n_elems
304
+ item_type = np.float64
305
+ elif ggml_type == GGMLQuantizationType.I8:
306
+ item_count = n_elems
307
+ item_type = np.int8
308
+ elif ggml_type == GGMLQuantizationType.I16:
309
+ item_count = n_elems
310
+ item_type = np.int16
311
+ elif ggml_type == GGMLQuantizationType.I32:
312
+ item_count = n_elems
313
+ item_type = np.int32
314
+ elif ggml_type == GGMLQuantizationType.I64:
315
+ item_count = n_elems
316
+ item_type = np.int64
317
+ else:
318
+ item_count = n_bytes
319
+ item_type = np.uint8
320
+ np_dims = quant_shape_to_byte_shape(np_dims, ggml_type)
321
+ tensors.append(
322
+ ReaderTensor(
323
+ name=tensor_name,
324
+ tensor_type=ggml_type,
325
+ shape=dims,
326
+ n_elements=n_elems,
327
+ n_bytes=n_bytes,
328
+ data_offset=data_offs,
329
+ data=self._get(data_offs, item_type, item_count).reshape(np_dims),
330
+ field=field,
331
+ )
332
+ )
333
+ self.tensors = tensors
modules_forge/packages/gguf/gguf_writer.py ADDED
@@ -0,0 +1,975 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import logging
4
+ import os
5
+ import shutil
6
+ import struct
7
+ import tempfile
8
+ from dataclasses import dataclass
9
+ from enum import Enum, auto
10
+ from io import BufferedWriter
11
+ from math import prod
12
+ from pathlib import Path
13
+ from string import ascii_letters, digits
14
+ from typing import IO, Any, Mapping, Sequence
15
+
16
+ import numpy as np
17
+
18
+ from .constants import (
19
+ GGUF_DEFAULT_ALIGNMENT,
20
+ GGUF_MAGIC,
21
+ GGUF_VERSION,
22
+ GGMLQuantizationType,
23
+ GGUFEndian,
24
+ GGUFValueType,
25
+ Keys,
26
+ PoolingType,
27
+ RopeScalingType,
28
+ TokenType,
29
+ )
30
+ from .quants import quant_shape_from_byte_shape
31
+
32
+ logger = logging.getLogger(__name__)
33
+
34
+
35
+ SHARD_NAME_FORMAT = "{:s}-{:05d}-of-{:05d}.gguf"
36
+
37
+
38
+ @dataclass
39
+ class TensorInfo:
40
+ shape: Sequence[int]
41
+ dtype: GGMLQuantizationType
42
+ nbytes: int
43
+ tensor: np.ndarray[Any, Any] | None = None
44
+
45
+
46
+ @dataclass
47
+ class GGUFValue:
48
+ value: Any
49
+ type: GGUFValueType
50
+
51
+
52
+ class WriterState(Enum):
53
+ NO_FILE = auto()
54
+ EMPTY = auto()
55
+ HEADER = auto()
56
+ KV_DATA = auto()
57
+ TI_DATA = auto()
58
+ WEIGHTS = auto()
59
+
60
+
61
+ class GGUFWriter:
62
+ fout: list[BufferedWriter] | None
63
+ path: Path | None
64
+ temp_file: tempfile.SpooledTemporaryFile[bytes] | None
65
+ tensors: list[dict[str, TensorInfo]]
66
+ kv_data: list[dict[str, GGUFValue]]
67
+ state: WriterState
68
+ _simple_value_packing = {
69
+ GGUFValueType.UINT8: "B",
70
+ GGUFValueType.INT8: "b",
71
+ GGUFValueType.UINT16: "H",
72
+ GGUFValueType.INT16: "h",
73
+ GGUFValueType.UINT32: "I",
74
+ GGUFValueType.INT32: "i",
75
+ GGUFValueType.FLOAT32: "f",
76
+ GGUFValueType.UINT64: "Q",
77
+ GGUFValueType.INT64: "q",
78
+ GGUFValueType.FLOAT64: "d",
79
+ GGUFValueType.BOOL: "?",
80
+ }
81
+
82
+ def __init__(
83
+ self,
84
+ path: os.PathLike[str] | str | None,
85
+ arch: str,
86
+ use_temp_file: bool = False,
87
+ endianess: GGUFEndian = GGUFEndian.LITTLE,
88
+ split_max_tensors: int = 0,
89
+ split_max_size: int = 0,
90
+ dry_run: bool = False,
91
+ small_first_shard: bool = False,
92
+ ):
93
+ self.fout = None
94
+ self.path = Path(path) if path else None
95
+ self.arch = arch
96
+ self.endianess = endianess
97
+ self.data_alignment = GGUF_DEFAULT_ALIGNMENT
98
+ self.use_temp_file = use_temp_file
99
+ self.temp_file = None
100
+ self.tensors = [{}]
101
+ self.kv_data = [{}]
102
+ self.split_max_tensors = split_max_tensors
103
+ self.split_max_size = split_max_size
104
+ self.dry_run = dry_run
105
+ self.small_first_shard = small_first_shard
106
+ logger.info(
107
+ "gguf: This GGUF file is for {0} Endian only".format(
108
+ "Big" if self.endianess == GGUFEndian.BIG else "Little",
109
+ )
110
+ )
111
+ self.state = WriterState.NO_FILE
112
+
113
+ if self.small_first_shard:
114
+ self.tensors.append({})
115
+
116
+ self.add_architecture()
117
+
118
+ def get_total_parameter_count(self) -> tuple[int, int, int, int]:
119
+ total_params = 0
120
+ shared_params = 0
121
+ expert_params = 0
122
+
123
+ expert_sum = 0
124
+ n_expert_tensors = 0
125
+
126
+ last_lora_a: tuple[str, TensorInfo] | None = None
127
+
128
+ for tensors in self.tensors:
129
+ for name, info in tensors.items():
130
+
131
+ shape = info.shape
132
+
133
+ if name.endswith(".lora_a"):
134
+ last_lora_a = (name, info)
135
+ continue
136
+ elif name.endswith(".lora_b"):
137
+ if last_lora_a is None or last_lora_a[0] != name[:-1] + "a":
138
+ # Bail when the LoRA pair can't be found trivially
139
+ logger.warning(
140
+ "can't measure LoRA size correctly, tensor order is unusual"
141
+ )
142
+ return 0, 0, 0, 0
143
+ else:
144
+ shape = (*shape[:-1], last_lora_a[1].shape[-1])
145
+
146
+ size = prod(shape)
147
+
148
+ if "_exps." in name:
149
+ expert_params += size // shape[-3]
150
+ expert_sum += shape[-3]
151
+ n_expert_tensors += 1
152
+ else:
153
+ shared_params += size
154
+
155
+ total_params += size
156
+
157
+ # Hopefully this should work even for variable-expert-count models
158
+ expert_count = (expert_sum // n_expert_tensors) if n_expert_tensors > 0 else 0
159
+
160
+ # Negate the total to signal it's likely not exact
161
+ if last_lora_a is not None:
162
+ total_params = -total_params
163
+
164
+ # NOTE: keep the output in the same order as accepted by 'size_label' in gguf-py/gguf/utility.py
165
+ return total_params, shared_params, expert_params, expert_count
166
+
167
+ def format_shard_names(self, path: Path) -> list[Path]:
168
+ if len(self.tensors) == 1:
169
+ return [path]
170
+ return [
171
+ path.with_name(
172
+ SHARD_NAME_FORMAT.format(path.stem, i + 1, len(self.tensors))
173
+ )
174
+ for i in range(len(self.tensors))
175
+ ]
176
+
177
+ def open_output_file(self, path: Path | None = None) -> None:
178
+ if (
179
+ self.state is WriterState.EMPTY
180
+ and self.fout is not None
181
+ and (path is None or path == self.path)
182
+ ):
183
+ # allow calling this multiple times as long as the path is the same
184
+ return
185
+
186
+ if self.state is not WriterState.NO_FILE:
187
+ raise ValueError(
188
+ f"Expected output file to be not yet opened, got {self.state}"
189
+ )
190
+
191
+ if path is not None:
192
+ self.path = path
193
+
194
+ if self.path is not None:
195
+ filenames = self.print_plan()
196
+ self.fout = [open(filename, "wb") for filename in filenames]
197
+ self.state = WriterState.EMPTY
198
+
199
+ def print_plan(self) -> list[Path]:
200
+ logger.info("Writing the following files:")
201
+ assert self.path is not None
202
+ filenames = self.format_shard_names(self.path)
203
+ assert len(filenames) == len(self.tensors)
204
+ for name, tensors in zip(filenames, self.tensors):
205
+ logger.info(
206
+ f"{name}: n_tensors = {len(tensors)}, total_size = {GGUFWriter.format_n_bytes_to_str(sum(ti.nbytes for ti in tensors.values()))}"
207
+ )
208
+
209
+ if self.dry_run:
210
+ logger.info("Dry run, not writing files")
211
+ for name in filenames:
212
+ print(name) # noqa: NP100
213
+ exit()
214
+
215
+ return filenames
216
+
217
+ def add_shard_kv_data(self) -> None:
218
+ if len(self.tensors) == 1:
219
+ return
220
+
221
+ total_tensors = sum(len(t) for t in self.tensors)
222
+ assert self.fout is not None
223
+ total_splits = len(self.fout)
224
+ self.kv_data.extend({} for _ in range(len(self.kv_data), total_splits))
225
+ for i, kv_data in enumerate(self.kv_data):
226
+ kv_data[Keys.Split.LLM_KV_SPLIT_NO] = GGUFValue(i, GGUFValueType.UINT16)
227
+ kv_data[Keys.Split.LLM_KV_SPLIT_COUNT] = GGUFValue(
228
+ total_splits, GGUFValueType.UINT16
229
+ )
230
+ kv_data[Keys.Split.LLM_KV_SPLIT_TENSORS_COUNT] = GGUFValue(
231
+ total_tensors, GGUFValueType.INT32
232
+ )
233
+
234
+ def write_header_to_file(self, path: Path | None = None) -> None:
235
+ if len(self.tensors) == 1 and (
236
+ self.split_max_tensors != 0 or self.split_max_size != 0
237
+ ):
238
+ logger.warning("Model fails split requirements, not splitting")
239
+
240
+ self.open_output_file(path)
241
+
242
+ if self.state is not WriterState.EMPTY:
243
+ raise ValueError(f"Expected output file to be empty, got {self.state}")
244
+
245
+ assert self.fout is not None
246
+ assert len(self.fout) == len(self.tensors)
247
+ assert len(self.kv_data) == 1
248
+
249
+ self.add_shard_kv_data()
250
+
251
+ for fout, tensors, kv_data in zip(self.fout, self.tensors, self.kv_data):
252
+ fout.write(self._pack("<I", GGUF_MAGIC, skip_pack_prefix=True))
253
+ fout.write(self._pack("I", GGUF_VERSION))
254
+ fout.write(self._pack("Q", len(tensors)))
255
+ fout.write(self._pack("Q", len(kv_data)))
256
+ fout.flush()
257
+ self.state = WriterState.HEADER
258
+
259
+ def write_kv_data_to_file(self) -> None:
260
+ if self.state is not WriterState.HEADER:
261
+ raise ValueError(
262
+ f"Expected output file to contain the header, got {self.state}"
263
+ )
264
+ assert self.fout is not None
265
+
266
+ for fout, kv_data in zip(self.fout, self.kv_data):
267
+ kv_bytes = bytearray()
268
+
269
+ for key, val in kv_data.items():
270
+ kv_bytes += self._pack_val(key, GGUFValueType.STRING, add_vtype=False)
271
+ kv_bytes += self._pack_val(val.value, val.type, add_vtype=True)
272
+
273
+ fout.write(kv_bytes)
274
+
275
+ self.flush()
276
+ self.state = WriterState.KV_DATA
277
+
278
+ def write_ti_data_to_file(self) -> None:
279
+ if self.state is not WriterState.KV_DATA:
280
+ raise ValueError(
281
+ f"Expected output file to contain KV data, got {self.state}"
282
+ )
283
+ assert self.fout is not None
284
+
285
+ for fout, tensors in zip(self.fout, self.tensors):
286
+ ti_data = bytearray()
287
+ offset_tensor = 0
288
+
289
+ for name, ti in tensors.items():
290
+ ti_data += self._pack_val(name, GGUFValueType.STRING, add_vtype=False)
291
+ n_dims = len(ti.shape)
292
+ ti_data += self._pack("I", n_dims)
293
+ for j in range(n_dims):
294
+ ti_data += self._pack("Q", ti.shape[n_dims - 1 - j])
295
+ ti_data += self._pack("I", ti.dtype)
296
+ ti_data += self._pack("Q", offset_tensor)
297
+ offset_tensor += GGUFWriter.ggml_pad(ti.nbytes, self.data_alignment)
298
+
299
+ fout.write(ti_data)
300
+ fout.flush()
301
+ self.state = WriterState.TI_DATA
302
+
303
+ def add_key_value(self, key: str, val: Any, vtype: GGUFValueType) -> None:
304
+ if any(key in kv_data for kv_data in self.kv_data):
305
+ raise ValueError(f"Duplicated key name {key!r}")
306
+
307
+ self.kv_data[0][key] = GGUFValue(value=val, type=vtype)
308
+
309
+ def add_uint8(self, key: str, val: int) -> None:
310
+ self.add_key_value(key, val, GGUFValueType.UINT8)
311
+
312
+ def add_int8(self, key: str, val: int) -> None:
313
+ self.add_key_value(key, val, GGUFValueType.INT8)
314
+
315
+ def add_uint16(self, key: str, val: int) -> None:
316
+ self.add_key_value(key, val, GGUFValueType.UINT16)
317
+
318
+ def add_int16(self, key: str, val: int) -> None:
319
+ self.add_key_value(key, val, GGUFValueType.INT16)
320
+
321
+ def add_uint32(self, key: str, val: int) -> None:
322
+ self.add_key_value(key, val, GGUFValueType.UINT32)
323
+
324
+ def add_int32(self, key: str, val: int) -> None:
325
+ self.add_key_value(key, val, GGUFValueType.INT32)
326
+
327
+ def add_float32(self, key: str, val: float) -> None:
328
+ self.add_key_value(key, val, GGUFValueType.FLOAT32)
329
+
330
+ def add_uint64(self, key: str, val: int) -> None:
331
+ self.add_key_value(key, val, GGUFValueType.UINT64)
332
+
333
+ def add_int64(self, key: str, val: int) -> None:
334
+ self.add_key_value(key, val, GGUFValueType.INT64)
335
+
336
+ def add_float64(self, key: str, val: float) -> None:
337
+ self.add_key_value(key, val, GGUFValueType.FLOAT64)
338
+
339
+ def add_bool(self, key: str, val: bool) -> None:
340
+ self.add_key_value(key, val, GGUFValueType.BOOL)
341
+
342
+ def add_string(self, key: str, val: str) -> None:
343
+ if not val:
344
+ return
345
+ self.add_key_value(key, val, GGUFValueType.STRING)
346
+
347
+ def add_array(self, key: str, val: Sequence[Any]) -> None:
348
+ if len(val) == 0:
349
+ return
350
+ self.add_key_value(key, val, GGUFValueType.ARRAY)
351
+
352
+ @staticmethod
353
+ def ggml_pad(x: int, n: int) -> int:
354
+ return ((x + n - 1) // n) * n
355
+
356
+ def add_tensor_info(
357
+ self,
358
+ name: str,
359
+ tensor_shape: Sequence[int],
360
+ tensor_dtype: np.dtype,
361
+ tensor_nbytes: int,
362
+ raw_dtype: GGMLQuantizationType | None = None,
363
+ ) -> None:
364
+ if self.state is not WriterState.NO_FILE:
365
+ raise ValueError(
366
+ f"Expected output file to be not yet opened, got {self.state}"
367
+ )
368
+
369
+ if any(name in tensors for tensors in self.tensors):
370
+ raise ValueError(f"Duplicated tensor name {name!r}")
371
+
372
+ if raw_dtype is None:
373
+ if tensor_dtype == np.float16:
374
+ dtype = GGMLQuantizationType.F16
375
+ elif tensor_dtype == np.float32:
376
+ dtype = GGMLQuantizationType.F32
377
+ elif tensor_dtype == np.float64:
378
+ dtype = GGMLQuantizationType.F64
379
+ elif tensor_dtype == np.int8:
380
+ dtype = GGMLQuantizationType.I8
381
+ elif tensor_dtype == np.int16:
382
+ dtype = GGMLQuantizationType.I16
383
+ elif tensor_dtype == np.int32:
384
+ dtype = GGMLQuantizationType.I32
385
+ elif tensor_dtype == np.int64:
386
+ dtype = GGMLQuantizationType.I64
387
+ else:
388
+ raise ValueError(
389
+ "Only F16, F32, F64, I8, I16, I32, I64 tensors are supported for now"
390
+ )
391
+ else:
392
+ dtype = raw_dtype
393
+ if tensor_dtype == np.uint8:
394
+ tensor_shape = quant_shape_from_byte_shape(tensor_shape, raw_dtype)
395
+
396
+ # make sure there is at least one tensor before splitting
397
+ if len(self.tensors[-1]) > 0:
398
+ if ( # split when over tensor limit
399
+ self.split_max_tensors != 0
400
+ and len(self.tensors[-1]) >= self.split_max_tensors
401
+ ) or ( # split when over size limit
402
+ self.split_max_size != 0
403
+ and sum(ti.nbytes for ti in self.tensors[-1].values()) + tensor_nbytes
404
+ > self.split_max_size
405
+ ):
406
+ self.tensors.append({})
407
+
408
+ self.tensors[-1][name] = TensorInfo(
409
+ shape=tensor_shape, dtype=dtype, nbytes=tensor_nbytes
410
+ )
411
+
412
+ def add_tensor(
413
+ self,
414
+ name: str,
415
+ tensor: np.ndarray[Any, Any],
416
+ raw_shape: Sequence[int] | None = None,
417
+ raw_dtype: GGMLQuantizationType | None = None,
418
+ ) -> None:
419
+ if self.endianess == GGUFEndian.BIG:
420
+ tensor.byteswap(inplace=True)
421
+ if self.use_temp_file and self.temp_file is None:
422
+ fp = tempfile.SpooledTemporaryFile(mode="w+b", max_size=256 * 1024 * 1024)
423
+ fp.seek(0)
424
+ self.temp_file = fp
425
+
426
+ shape: Sequence[int] = raw_shape if raw_shape is not None else tensor.shape
427
+ self.add_tensor_info(
428
+ name, shape, tensor.dtype, tensor.nbytes, raw_dtype=raw_dtype
429
+ )
430
+
431
+ if self.temp_file is None:
432
+ self.tensors[-1][name].tensor = tensor
433
+ return
434
+
435
+ tensor.tofile(self.temp_file)
436
+ self.write_padding(self.temp_file, tensor.nbytes)
437
+
438
+ def write_padding(self, fp: IO[bytes], n: int, align: int | None = None) -> None:
439
+ pad = (
440
+ GGUFWriter.ggml_pad(n, align if align is not None else self.data_alignment)
441
+ - n
442
+ )
443
+ if pad != 0:
444
+ fp.write(bytes([0] * pad))
445
+
446
+ def write_tensor_data(self, tensor: np.ndarray[Any, Any]) -> None:
447
+ if (
448
+ self.state is not WriterState.TI_DATA
449
+ and self.state is not WriterState.WEIGHTS
450
+ ):
451
+ raise ValueError(
452
+ f"Expected output file to contain tensor info or weights, got {self.state}"
453
+ )
454
+ assert self.fout is not None
455
+
456
+ if self.endianess == GGUFEndian.BIG:
457
+ tensor.byteswap(inplace=True)
458
+
459
+ file_id = -1
460
+ for i, tensors in enumerate(self.tensors):
461
+ if len(tensors) > 0:
462
+ file_id = i
463
+ break
464
+
465
+ fout = self.fout[file_id]
466
+
467
+ # pop the first tensor info
468
+ # TODO: cleaner way to get the first key
469
+ first_tensor_name = [
470
+ name for name, _ in zip(self.tensors[file_id].keys(), range(1))
471
+ ][0]
472
+ ti = self.tensors[file_id].pop(first_tensor_name)
473
+ assert ti.nbytes == tensor.nbytes
474
+
475
+ self.write_padding(fout, fout.tell())
476
+ tensor.tofile(fout)
477
+ self.write_padding(fout, tensor.nbytes)
478
+
479
+ self.state = WriterState.WEIGHTS
480
+
481
+ def write_tensors_to_file(self, *, progress: bool = False) -> None:
482
+ self.write_ti_data_to_file()
483
+
484
+ assert self.fout is not None
485
+
486
+ for fout in self.fout:
487
+ self.write_padding(fout, fout.tell())
488
+
489
+ if self.temp_file is None:
490
+ shard_bar = None
491
+ bar = None
492
+
493
+ if progress:
494
+ from tqdm import tqdm
495
+
496
+ total_bytes = sum(ti.nbytes for t in self.tensors for ti in t.values())
497
+
498
+ if len(self.fout) > 1:
499
+ shard_bar = tqdm(
500
+ desc=f"Shard (0/{len(self.fout)})",
501
+ total=None,
502
+ unit="byte",
503
+ unit_scale=True,
504
+ )
505
+ bar = tqdm(
506
+ desc="Writing", total=total_bytes, unit="byte", unit_scale=True
507
+ )
508
+
509
+ for i, (fout, tensors) in enumerate(zip(self.fout, self.tensors)):
510
+ if shard_bar is not None:
511
+ shard_bar.set_description(f"Shard ({i + 1}/{len(self.fout)})")
512
+ total = sum(ti.nbytes for ti in tensors.values())
513
+ shard_bar.reset(total=(total if total > 0 else None))
514
+
515
+ # relying on the fact that Python dicts preserve insertion order (since 3.7)
516
+ for ti in tensors.values():
517
+ assert (
518
+ ti.tensor is not None
519
+ ) # can only iterate once over the tensors
520
+ assert ti.tensor.nbytes == ti.nbytes
521
+ ti.tensor.tofile(fout)
522
+ if shard_bar is not None:
523
+ shard_bar.update(ti.nbytes)
524
+ if bar is not None:
525
+ bar.update(ti.nbytes)
526
+ self.write_padding(fout, ti.nbytes)
527
+ ti.tensor = None
528
+ else:
529
+ self.temp_file.seek(0)
530
+
531
+ shutil.copyfileobj(
532
+ self.temp_file, self.fout[0 if not self.small_first_shard else 1]
533
+ )
534
+ self.flush()
535
+ self.temp_file.close()
536
+
537
+ self.state = WriterState.WEIGHTS
538
+
539
+ def flush(self) -> None:
540
+ assert self.fout is not None
541
+ for fout in self.fout:
542
+ fout.flush()
543
+
544
+ def close(self) -> None:
545
+ if self.fout is not None:
546
+ for fout in self.fout:
547
+ fout.close()
548
+ self.fout = None
549
+
550
+ def add_type(self, type_name: str) -> None:
551
+ self.add_string(Keys.General.TYPE, type_name)
552
+
553
+ def add_architecture(self) -> None:
554
+ self.add_string(Keys.General.ARCHITECTURE, self.arch)
555
+
556
+ def add_quantization_version(self, quantization_version: int) -> None:
557
+ self.add_uint32(Keys.General.QUANTIZATION_VERSION, quantization_version)
558
+
559
+ def add_custom_alignment(self, alignment: int) -> None:
560
+ self.data_alignment = alignment
561
+ self.add_uint32(Keys.General.ALIGNMENT, alignment)
562
+
563
+ def add_file_type(self, ftype: int) -> None:
564
+ self.add_uint32(Keys.General.FILE_TYPE, ftype)
565
+
566
+ def add_name(self, name: str) -> None:
567
+ self.add_string(Keys.General.NAME, name)
568
+
569
+ def add_author(self, author: str) -> None:
570
+ self.add_string(Keys.General.AUTHOR, author)
571
+
572
+ def add_version(self, version: str) -> None:
573
+ self.add_string(Keys.General.VERSION, version)
574
+
575
+ def add_organization(self, organization: str) -> None:
576
+ self.add_string(Keys.General.ORGANIZATION, organization)
577
+
578
+ def add_finetune(self, finetune: str) -> None:
579
+ self.add_string(Keys.General.FINETUNE, finetune)
580
+
581
+ def add_basename(self, basename: str) -> None:
582
+ self.add_string(Keys.General.BASENAME, basename)
583
+
584
+ def add_description(self, description: str) -> None:
585
+ self.add_string(Keys.General.DESCRIPTION, description)
586
+
587
+ def add_quantized_by(self, quantized: str) -> None:
588
+ self.add_string(Keys.General.QUANTIZED_BY, quantized)
589
+
590
+ def add_size_label(self, size_label: str) -> None:
591
+ self.add_string(Keys.General.SIZE_LABEL, size_label)
592
+
593
+ def add_license(self, license: str) -> None:
594
+ self.add_string(Keys.General.LICENSE, license)
595
+
596
+ def add_license_name(self, license: str) -> None:
597
+ self.add_string(Keys.General.LICENSE_NAME, license)
598
+
599
+ def add_license_link(self, license: str) -> None:
600
+ self.add_string(Keys.General.LICENSE_LINK, license)
601
+
602
+ def add_url(self, url: str) -> None:
603
+ self.add_string(Keys.General.URL, url)
604
+
605
+ def add_doi(self, doi: str) -> None:
606
+ self.add_string(Keys.General.DOI, doi)
607
+
608
+ def add_uuid(self, uuid: str) -> None:
609
+ self.add_string(Keys.General.UUID, uuid)
610
+
611
+ def add_repo_url(self, repo_url: str) -> None:
612
+ self.add_string(Keys.General.REPO_URL, repo_url)
613
+
614
+ def add_source_url(self, url: str) -> None:
615
+ self.add_string(Keys.General.SOURCE_URL, url)
616
+
617
+ def add_source_doi(self, doi: str) -> None:
618
+ self.add_string(Keys.General.SOURCE_DOI, doi)
619
+
620
+ def add_source_uuid(self, uuid: str) -> None:
621
+ self.add_string(Keys.General.SOURCE_UUID, uuid)
622
+
623
+ def add_source_repo_url(self, repo_url: str) -> None:
624
+ self.add_string(Keys.General.SOURCE_REPO_URL, repo_url)
625
+
626
+ def add_base_model_count(self, source_count: int) -> None:
627
+ self.add_uint32(Keys.General.BASE_MODEL_COUNT, source_count)
628
+
629
+ def add_base_model_name(self, source_id: int, name: str) -> None:
630
+ self.add_string(Keys.General.BASE_MODEL_NAME.format(id=source_id), name)
631
+
632
+ def add_base_model_author(self, source_id: int, author: str) -> None:
633
+ self.add_string(Keys.General.BASE_MODEL_AUTHOR.format(id=source_id), author)
634
+
635
+ def add_base_model_version(self, source_id: int, version: str) -> None:
636
+ self.add_string(Keys.General.BASE_MODEL_VERSION.format(id=source_id), version)
637
+
638
+ def add_base_model_organization(self, source_id: int, organization: str) -> None:
639
+ self.add_string(
640
+ Keys.General.BASE_MODEL_ORGANIZATION.format(id=source_id), organization
641
+ )
642
+
643
+ def add_base_model_url(self, source_id: int, url: str) -> None:
644
+ self.add_string(Keys.General.BASE_MODEL_URL.format(id=source_id), url)
645
+
646
+ def add_base_model_doi(self, source_id: int, doi: str) -> None:
647
+ self.add_string(Keys.General.BASE_MODEL_DOI.format(id=source_id), doi)
648
+
649
+ def add_base_model_uuid(self, source_id: int, uuid: str) -> None:
650
+ self.add_string(Keys.General.BASE_MODEL_UUID.format(id=source_id), uuid)
651
+
652
+ def add_base_model_repo_url(self, source_id: int, repo_url: str) -> None:
653
+ self.add_string(Keys.General.BASE_MODEL_REPO_URL.format(id=source_id), repo_url)
654
+
655
+ def add_tags(self, tags: Sequence[str]) -> None:
656
+ self.add_array(Keys.General.TAGS, tags)
657
+
658
+ def add_languages(self, languages: Sequence[str]) -> None:
659
+ self.add_array(Keys.General.LANGUAGES, languages)
660
+
661
+ def add_datasets(self, datasets: Sequence[str]) -> None:
662
+ self.add_array(Keys.General.DATASETS, datasets)
663
+
664
+ def add_tensor_data_layout(self, layout: str) -> None:
665
+ self.add_string(Keys.LLM.TENSOR_DATA_LAYOUT.format(arch=self.arch), layout)
666
+
667
+ def add_vocab_size(self, size: int) -> None:
668
+ self.add_uint32(Keys.LLM.VOCAB_SIZE.format(arch=self.arch), size)
669
+
670
+ def add_context_length(self, length: int) -> None:
671
+ self.add_uint32(Keys.LLM.CONTEXT_LENGTH.format(arch=self.arch), length)
672
+
673
+ def add_embedding_length(self, length: int) -> None:
674
+ self.add_uint32(Keys.LLM.EMBEDDING_LENGTH.format(arch=self.arch), length)
675
+
676
+ def add_block_count(self, length: int) -> None:
677
+ self.add_uint32(Keys.LLM.BLOCK_COUNT.format(arch=self.arch), length)
678
+
679
+ def add_leading_dense_block_count(self, length: int) -> None:
680
+ self.add_uint32(
681
+ Keys.LLM.LEADING_DENSE_BLOCK_COUNT.format(arch=self.arch), length
682
+ )
683
+
684
+ def add_feed_forward_length(self, length: int | Sequence[int]) -> None:
685
+ if isinstance(length, int):
686
+ self.add_uint32(Keys.LLM.FEED_FORWARD_LENGTH.format(arch=self.arch), length)
687
+ else:
688
+ self.add_array(Keys.LLM.FEED_FORWARD_LENGTH.format(arch=self.arch), length)
689
+
690
+ def add_expert_feed_forward_length(self, length: int) -> None:
691
+ self.add_uint32(
692
+ Keys.LLM.EXPERT_FEED_FORWARD_LENGTH.format(arch=self.arch), length
693
+ )
694
+
695
+ def add_expert_shared_feed_forward_length(self, length: int) -> None:
696
+ self.add_uint32(
697
+ Keys.LLM.EXPERT_SHARED_FEED_FORWARD_LENGTH.format(arch=self.arch), length
698
+ )
699
+
700
+ def add_parallel_residual(self, use: bool) -> None:
701
+ self.add_bool(Keys.LLM.USE_PARALLEL_RESIDUAL.format(arch=self.arch), use)
702
+
703
+ def add_decoder_start_token_id(self, id: int) -> None:
704
+ self.add_uint32(Keys.LLM.DECODER_START_TOKEN_ID.format(arch=self.arch), id)
705
+
706
+ def add_head_count(self, count: int | Sequence[int]) -> None:
707
+ if isinstance(count, int):
708
+ self.add_uint32(Keys.Attention.HEAD_COUNT.format(arch=self.arch), count)
709
+ else:
710
+ self.add_array(Keys.Attention.HEAD_COUNT.format(arch=self.arch), count)
711
+
712
+ def add_head_count_kv(self, count: int | Sequence[int]) -> None:
713
+ if isinstance(count, int):
714
+ self.add_uint32(Keys.Attention.HEAD_COUNT_KV.format(arch=self.arch), count)
715
+ else:
716
+ self.add_array(Keys.Attention.HEAD_COUNT_KV.format(arch=self.arch), count)
717
+
718
+ def add_key_length(self, length: int) -> None:
719
+ self.add_uint32(Keys.Attention.KEY_LENGTH.format(arch=self.arch), length)
720
+
721
+ def add_value_length(self, length: int) -> None:
722
+ self.add_uint32(Keys.Attention.VALUE_LENGTH.format(arch=self.arch), length)
723
+
724
+ def add_max_alibi_bias(self, bias: float) -> None:
725
+ self.add_float32(Keys.Attention.MAX_ALIBI_BIAS.format(arch=self.arch), bias)
726
+
727
+ def add_clamp_kqv(self, value: float) -> None:
728
+ self.add_float32(Keys.Attention.CLAMP_KQV.format(arch=self.arch), value)
729
+
730
+ def add_logit_scale(self, value: float) -> None:
731
+ self.add_float32(Keys.LLM.LOGIT_SCALE.format(arch=self.arch), value)
732
+
733
+ def add_attn_logit_softcapping(self, value: float) -> None:
734
+ self.add_float32(Keys.LLM.ATTN_LOGIT_SOFTCAPPING.format(arch=self.arch), value)
735
+
736
+ def add_final_logit_softcapping(self, value: float) -> None:
737
+ self.add_float32(Keys.LLM.FINAL_LOGIT_SOFTCAPPING.format(arch=self.arch), value)
738
+
739
+ def add_expert_count(self, count: int) -> None:
740
+ self.add_uint32(Keys.LLM.EXPERT_COUNT.format(arch=self.arch), count)
741
+
742
+ def add_expert_used_count(self, count: int) -> None:
743
+ self.add_uint32(Keys.LLM.EXPERT_USED_COUNT.format(arch=self.arch), count)
744
+
745
+ def add_expert_shared_count(self, count: int) -> None:
746
+ self.add_uint32(Keys.LLM.EXPERT_SHARED_COUNT.format(arch=self.arch), count)
747
+
748
+ def add_expert_weights_scale(self, value: float) -> None:
749
+ self.add_float32(Keys.LLM.EXPERT_WEIGHTS_SCALE.format(arch=self.arch), value)
750
+
751
+ def add_layer_norm_eps(self, value: float) -> None:
752
+ self.add_float32(Keys.Attention.LAYERNORM_EPS.format(arch=self.arch), value)
753
+
754
+ def add_layer_norm_rms_eps(self, value: float) -> None:
755
+ self.add_float32(Keys.Attention.LAYERNORM_RMS_EPS.format(arch=self.arch), value)
756
+
757
+ def add_causal_attention(self, value: bool) -> None:
758
+ self.add_bool(Keys.Attention.CAUSAL.format(arch=self.arch), value)
759
+
760
+ def add_q_lora_rank(self, length: int) -> None:
761
+ self.add_uint32(Keys.Attention.Q_LORA_RANK.format(arch=self.arch), length)
762
+
763
+ def add_kv_lora_rank(self, length: int) -> None:
764
+ self.add_uint32(Keys.Attention.KV_LORA_RANK.format(arch=self.arch), length)
765
+
766
+ def add_relative_attn_buckets_count(self, value: int) -> None:
767
+ self.add_uint32(Keys.Attention.REL_BUCKETS_COUNT.format(arch=self.arch), value)
768
+
769
+ def add_sliding_window(self, value: int) -> None:
770
+ self.add_uint32(Keys.Attention.SLIDING_WINDOW.format(arch=self.arch), value)
771
+
772
+ def add_pooling_type(self, value: PoolingType) -> None:
773
+ self.add_uint32(Keys.LLM.POOLING_TYPE.format(arch=self.arch), value.value)
774
+
775
+ def add_rope_dimension_count(self, count: int) -> None:
776
+ self.add_uint32(Keys.Rope.DIMENSION_COUNT.format(arch=self.arch), count)
777
+
778
+ def add_rope_freq_base(self, value: float) -> None:
779
+ self.add_float32(Keys.Rope.FREQ_BASE.format(arch=self.arch), value)
780
+
781
+ def add_rope_scaling_type(self, value: RopeScalingType) -> None:
782
+ self.add_string(Keys.Rope.SCALING_TYPE.format(arch=self.arch), value.value)
783
+
784
+ def add_rope_scaling_factor(self, value: float) -> None:
785
+ self.add_float32(Keys.Rope.SCALING_FACTOR.format(arch=self.arch), value)
786
+
787
+ def add_rope_scaling_attn_factors(self, value: float) -> None:
788
+ self.add_float32(Keys.Rope.SCALING_ATTN_FACTOR.format(arch=self.arch), value)
789
+
790
+ def add_rope_scaling_orig_ctx_len(self, value: int) -> None:
791
+ self.add_uint32(Keys.Rope.SCALING_ORIG_CTX_LEN.format(arch=self.arch), value)
792
+
793
+ def add_rope_scaling_finetuned(self, value: bool) -> None:
794
+ self.add_bool(Keys.Rope.SCALING_FINETUNED.format(arch=self.arch), value)
795
+
796
+ def add_rope_scaling_yarn_log_mul(self, value: float) -> None:
797
+ self.add_float32(Keys.Rope.SCALING_YARN_LOG_MUL.format(arch=self.arch), value)
798
+
799
+ def add_ssm_conv_kernel(self, value: int) -> None:
800
+ self.add_uint32(Keys.SSM.CONV_KERNEL.format(arch=self.arch), value)
801
+
802
+ def add_ssm_inner_size(self, value: int) -> None:
803
+ self.add_uint32(Keys.SSM.INNER_SIZE.format(arch=self.arch), value)
804
+
805
+ def add_ssm_state_size(self, value: int) -> None:
806
+ self.add_uint32(Keys.SSM.STATE_SIZE.format(arch=self.arch), value)
807
+
808
+ def add_ssm_time_step_rank(self, value: int) -> None:
809
+ self.add_uint32(Keys.SSM.TIME_STEP_RANK.format(arch=self.arch), value)
810
+
811
+ def add_tokenizer_model(self, model: str) -> None:
812
+ self.add_string(Keys.Tokenizer.MODEL, model)
813
+
814
+ def add_tokenizer_pre(self, pre: str) -> None:
815
+ self.add_string(Keys.Tokenizer.PRE, pre)
816
+
817
+ def add_token_list(
818
+ self, tokens: Sequence[str] | Sequence[bytes] | Sequence[bytearray]
819
+ ) -> None:
820
+ self.add_array(Keys.Tokenizer.LIST, tokens)
821
+
822
+ def add_token_merges(
823
+ self, merges: Sequence[str] | Sequence[bytes] | Sequence[bytearray]
824
+ ) -> None:
825
+ self.add_array(Keys.Tokenizer.MERGES, merges)
826
+
827
+ def add_token_types(self, types: Sequence[TokenType] | Sequence[int]) -> None:
828
+ self.add_array(Keys.Tokenizer.TOKEN_TYPE, types)
829
+
830
+ def add_token_type_count(self, value: int) -> None:
831
+ self.add_uint32(Keys.Tokenizer.TOKEN_TYPE_COUNT, value)
832
+
833
+ def add_token_scores(self, scores: Sequence[float]) -> None:
834
+ self.add_array(Keys.Tokenizer.SCORES, scores)
835
+
836
+ def add_bos_token_id(self, id: int) -> None:
837
+ self.add_uint32(Keys.Tokenizer.BOS_ID, id)
838
+
839
+ def add_eos_token_id(self, id: int) -> None:
840
+ self.add_uint32(Keys.Tokenizer.EOS_ID, id)
841
+
842
+ def add_unk_token_id(self, id: int) -> None:
843
+ self.add_uint32(Keys.Tokenizer.UNK_ID, id)
844
+
845
+ def add_sep_token_id(self, id: int) -> None:
846
+ self.add_uint32(Keys.Tokenizer.SEP_ID, id)
847
+
848
+ def add_pad_token_id(self, id: int) -> None:
849
+ self.add_uint32(Keys.Tokenizer.PAD_ID, id)
850
+
851
+ def add_cls_token_id(self, id: int) -> None:
852
+ self.add_uint32(Keys.Tokenizer.CLS_ID, id)
853
+
854
+ def add_mask_token_id(self, id: int) -> None:
855
+ self.add_uint32(Keys.Tokenizer.MASK_ID, id)
856
+
857
+ def add_add_bos_token(self, value: bool) -> None:
858
+ self.add_bool(Keys.Tokenizer.ADD_BOS, value)
859
+
860
+ def add_add_eos_token(self, value: bool) -> None:
861
+ self.add_bool(Keys.Tokenizer.ADD_EOS, value)
862
+
863
+ def add_add_space_prefix(self, value: bool) -> None:
864
+ self.add_bool(Keys.Tokenizer.ADD_PREFIX, value)
865
+
866
+ def add_remove_extra_whitespaces(self, value: bool) -> None:
867
+ self.add_bool(Keys.Tokenizer.REMOVE_EXTRA_WS, value)
868
+
869
+ def add_precompiled_charsmap(self, charsmap: Sequence[bytes]) -> None:
870
+ self.add_array(Keys.Tokenizer.PRECOMPILED_CHARSMAP, charsmap)
871
+
872
+ def add_chat_template(self, value: str | Sequence[Mapping[str, str]]) -> None:
873
+ if not isinstance(value, str):
874
+ template_default = None
875
+ template_names = set()
876
+
877
+ for choice in value:
878
+ name = choice.get("name", "")
879
+ template = choice.get("template")
880
+
881
+ # Allowing non-alphanumerical characters in template name is probably not a good idea, so filter it
882
+ name = "".join(
883
+ (c if c in ascii_letters + digits else "_" for c in name)
884
+ )
885
+
886
+ if name and template is not None:
887
+ if name == "default":
888
+ template_default = template
889
+ else:
890
+ template_names.add(name)
891
+ self.add_string(
892
+ Keys.Tokenizer.CHAT_TEMPLATE_N.format(name=name), template
893
+ )
894
+
895
+ if template_names:
896
+ self.add_array(Keys.Tokenizer.CHAT_TEMPLATES, list(template_names))
897
+
898
+ if template_default is None:
899
+ return
900
+
901
+ value = template_default
902
+
903
+ self.add_string(Keys.Tokenizer.CHAT_TEMPLATE, value)
904
+
905
+ def add_prefix_token_id(self, id: int) -> None:
906
+ self.add_uint32(Keys.Tokenizer.PREFIX_ID, id)
907
+
908
+ def add_suffix_token_id(self, id: int) -> None:
909
+ self.add_uint32(Keys.Tokenizer.SUFFIX_ID, id)
910
+
911
+ def add_middle_token_id(self, id: int) -> None:
912
+ self.add_uint32(Keys.Tokenizer.MIDDLE_ID, id)
913
+
914
+ def add_eot_token_id(self, id: int) -> None:
915
+ self.add_uint32(Keys.Tokenizer.EOT_ID, id)
916
+
917
+ def add_eom_token_id(self, id: int) -> None:
918
+ self.add_uint32(Keys.Tokenizer.EOM_ID, id)
919
+
920
+ def _pack(self, fmt: str, value: Any, skip_pack_prefix: bool = False) -> bytes:
921
+ pack_prefix = ""
922
+ if not skip_pack_prefix:
923
+ pack_prefix = "<" if self.endianess == GGUFEndian.LITTLE else ">"
924
+ return struct.pack(f"{pack_prefix}{fmt}", value)
925
+
926
+ def _pack_val(self, val: Any, vtype: GGUFValueType, add_vtype: bool) -> bytes:
927
+ kv_data = bytearray()
928
+
929
+ if add_vtype:
930
+ kv_data += self._pack("I", vtype)
931
+
932
+ pack_fmt = self._simple_value_packing.get(vtype)
933
+ if pack_fmt is not None:
934
+ kv_data += self._pack(
935
+ pack_fmt, val, skip_pack_prefix=vtype == GGUFValueType.BOOL
936
+ )
937
+ elif vtype == GGUFValueType.STRING:
938
+ encoded_val = val.encode("utf-8") if isinstance(val, str) else val
939
+ kv_data += self._pack("Q", len(encoded_val))
940
+ kv_data += encoded_val
941
+ elif vtype == GGUFValueType.ARRAY:
942
+
943
+ if not isinstance(val, Sequence):
944
+ raise ValueError("Invalid GGUF metadata array, expecting sequence")
945
+
946
+ if len(val) == 0:
947
+ raise ValueError("Invalid GGUF metadata array. Empty array")
948
+
949
+ if isinstance(val, bytes):
950
+ ltype = GGUFValueType.UINT8
951
+ else:
952
+ ltype = GGUFValueType.get_type(val[0])
953
+ if not all(GGUFValueType.get_type(i) is ltype for i in val[1:]):
954
+ raise ValueError(
955
+ "All items in a GGUF array should be of the same type"
956
+ )
957
+ kv_data += self._pack("I", ltype)
958
+ kv_data += self._pack("Q", len(val))
959
+ for item in val:
960
+ kv_data += self._pack_val(item, ltype, add_vtype=False)
961
+ else:
962
+ raise ValueError("Invalid GGUF metadata value type or value")
963
+
964
+ return kv_data
965
+
966
+ @staticmethod
967
+ def format_n_bytes_to_str(num: int) -> str:
968
+ if num == 0:
969
+ return "negligible - metadata only"
970
+ fnum = float(num)
971
+ for unit in ("", "K", "M", "G"):
972
+ if abs(fnum) < 1000.0:
973
+ return f"{fnum:3.1f}{unit}"
974
+ fnum /= 1000.0
975
+ return f"{fnum:.1f}T - over 1TB, split recommended"
modules_forge/packages/gguf/lazy.py ADDED
@@ -0,0 +1,286 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import logging
4
+ from abc import ABC, ABCMeta, abstractmethod
5
+ from typing import Any, Callable
6
+
7
+ import numpy as np
8
+ from numpy.typing import DTypeLike
9
+
10
+ logger = logging.getLogger(__name__)
11
+
12
+
13
+ class LazyMeta(ABCMeta):
14
+
15
+ def __new__(
16
+ cls, name: str, bases: tuple[type, ...], namespace: dict[str, Any], **kwargs
17
+ ):
18
+ def __getattr__(self, name: str) -> Any:
19
+ meta_attr = getattr(self._meta, name)
20
+ if callable(meta_attr):
21
+ return type(self)._wrap_fn(
22
+ (lambda s, *args, **kwargs: getattr(s, name)(*args, **kwargs)),
23
+ use_self=self,
24
+ )
25
+ elif isinstance(meta_attr, self._tensor_type):
26
+ # e.g. self.T with torch.Tensor should still be wrapped
27
+ return type(self)._wrap_fn(lambda s: getattr(s, name))(self)
28
+ else:
29
+ # no need to wrap non-tensor properties,
30
+ # and they likely don't depend on the actual contents of the tensor
31
+ return meta_attr
32
+
33
+ namespace["__getattr__"] = __getattr__
34
+
35
+ # need to make a builder for the wrapped wrapper to copy the name,
36
+ # or else it fails with very cryptic error messages,
37
+ # because somehow the same string would end up in every closures
38
+ def mk_wrap(op_name: str, *, meta_noop: bool = False):
39
+ # need to wrap the wrapper to get self
40
+ def wrapped_special_op(self, *args, **kwargs):
41
+ return type(self)._wrap_fn(
42
+ getattr(type(self)._tensor_type, op_name),
43
+ meta_noop=meta_noop,
44
+ )(self, *args, **kwargs)
45
+
46
+ return wrapped_special_op
47
+
48
+ # special methods bypass __getattr__, so they need to be added manually
49
+ # ref: https://docs.python.org/3/reference/datamodel.html#special-lookup
50
+ # NOTE: doing this from a metaclass is very convenient
51
+ # TODO: make this even more comprehensive
52
+ for binary_op in (
53
+ "lt",
54
+ "le",
55
+ "eq",
56
+ "ne",
57
+ "ge",
58
+ "gt",
59
+ "not" "abs",
60
+ "add",
61
+ "and",
62
+ "floordiv",
63
+ "invert",
64
+ "lshift",
65
+ "mod",
66
+ "mul",
67
+ "matmul",
68
+ "neg",
69
+ "or",
70
+ "pos",
71
+ "pow",
72
+ "rshift",
73
+ "sub",
74
+ "truediv",
75
+ "xor",
76
+ "iadd",
77
+ "iand",
78
+ "ifloordiv",
79
+ "ilshift",
80
+ "imod",
81
+ "imul",
82
+ "ior",
83
+ "irshift",
84
+ "isub",
85
+ "ixor",
86
+ "radd",
87
+ "rand",
88
+ "rfloordiv",
89
+ "rmul",
90
+ "ror",
91
+ "rpow",
92
+ "rsub",
93
+ "rtruediv",
94
+ "rxor",
95
+ ):
96
+ attr_name = f"__{binary_op}__"
97
+ # the result of these operators usually has the same shape and dtype as the input,
98
+ # so evaluation on the meta tensor can be skipped.
99
+ namespace[attr_name] = mk_wrap(attr_name, meta_noop=True)
100
+
101
+ for special_op in (
102
+ "getitem",
103
+ "setitem",
104
+ "len",
105
+ ):
106
+ attr_name = f"__{special_op}__"
107
+ namespace[attr_name] = mk_wrap(attr_name, meta_noop=False)
108
+
109
+ return super().__new__(cls, name, bases, namespace, **kwargs)
110
+
111
+
112
+ # Tree of lazy tensors
113
+ class LazyBase(ABC, metaclass=LazyMeta):
114
+ _tensor_type: type
115
+ _meta: Any
116
+ _data: Any | None
117
+ _args: tuple
118
+ _kwargs: dict[str, Any]
119
+ _func: Callable[[Any], Any] | None
120
+
121
+ def __init__(
122
+ self,
123
+ *,
124
+ meta: Any,
125
+ data: Any | None = None,
126
+ args: tuple = (),
127
+ kwargs: dict[str, Any] | None = None,
128
+ func: Callable[[Any], Any] | None = None,
129
+ ):
130
+ super().__init__()
131
+ self._meta = meta
132
+ self._data = data
133
+ self._args = args
134
+ self._kwargs = kwargs if kwargs is not None else {}
135
+ self._func = func
136
+ assert self._func is not None or self._data is not None
137
+
138
+ def __init_subclass__(cls) -> None:
139
+ if "_tensor_type" not in cls.__dict__:
140
+ raise TypeError(f"property '_tensor_type' must be defined for {cls!r}")
141
+ return super().__init_subclass__()
142
+
143
+ @staticmethod
144
+ def _recurse_apply(o: Any, fn: Callable[[Any], Any]) -> Any:
145
+ # TODO: dict and set
146
+ if isinstance(o, (list, tuple)):
147
+ L = []
148
+ for item in o:
149
+ L.append(LazyBase._recurse_apply(item, fn))
150
+ if isinstance(o, tuple):
151
+ L = tuple(L)
152
+ return L
153
+ elif isinstance(o, LazyBase):
154
+ return fn(o)
155
+ else:
156
+ return o
157
+
158
+ @classmethod
159
+ def _wrap_fn(
160
+ cls,
161
+ fn: Callable,
162
+ *,
163
+ use_self: LazyBase | None = None,
164
+ meta_noop: (
165
+ bool
166
+ | DTypeLike
167
+ | tuple[DTypeLike, Callable[[tuple[int, ...]], tuple[int, ...]]]
168
+ ) = False,
169
+ ) -> Callable[[Any], Any]:
170
+ def wrapped_fn(*args, **kwargs):
171
+ if kwargs is None:
172
+ kwargs = {}
173
+ args = ((use_self,) if use_self is not None else ()) + args
174
+
175
+ meta_args = LazyBase._recurse_apply(args, lambda t: t._meta)
176
+ # TODO: maybe handle tensors in kwargs too
177
+
178
+ if isinstance(meta_noop, bool) and not meta_noop:
179
+ try:
180
+ res = fn(*meta_args, **kwargs)
181
+ except NotImplementedError:
182
+ # running some operations on PyTorch's Meta tensors can cause this exception
183
+ res = None
184
+ else:
185
+ # some operators don't need to actually run on the meta tensors
186
+ assert len(args) > 0
187
+ res = args[0]
188
+ assert isinstance(res, cls)
189
+ res = res._meta
190
+ # allow operations to override the dtype and shape
191
+ if meta_noop is not True:
192
+ if isinstance(meta_noop, tuple):
193
+ dtype, shape = meta_noop
194
+ assert callable(shape)
195
+ res = cls.meta_with_dtype_and_shape(dtype, shape(res.shape))
196
+ else:
197
+ res = cls.meta_with_dtype_and_shape(meta_noop, res.shape)
198
+
199
+ if isinstance(res, cls._tensor_type):
200
+ return cls(
201
+ meta=cls.eager_to_meta(res), args=args, kwargs=kwargs, func=fn
202
+ )
203
+ else:
204
+ del res # not needed
205
+ # non-tensor return likely relies on the contents of the args
206
+ # (e.g. the result of torch.equal)
207
+ eager_args = cls.to_eager(args)
208
+ return fn(*eager_args, **kwargs)
209
+
210
+ return wrapped_fn
211
+
212
+ @classmethod
213
+ def to_eager(cls, t: Any) -> Any:
214
+ def simple_to_eager(_t: LazyBase) -> Any:
215
+ if _t._data is not None:
216
+ return _t._data
217
+
218
+ # NOTE: there's a recursion limit in Python (usually 1000)
219
+
220
+ assert _t._func is not None
221
+ _t._args = cls._recurse_apply(_t._args, simple_to_eager)
222
+ _t._data = _t._func(*_t._args, **_t._kwargs)
223
+ # sanity check
224
+ assert _t._data is not None
225
+ assert _t._data.dtype == _t._meta.dtype
226
+ assert _t._data.shape == _t._meta.shape
227
+
228
+ return _t._data
229
+
230
+ # recurse into lists and/or tuples, keeping their structure
231
+ return cls._recurse_apply(t, simple_to_eager)
232
+
233
+ @classmethod
234
+ def eager_to_meta(cls, t: Any) -> Any:
235
+ return cls.meta_with_dtype_and_shape(t.dtype, t.shape)
236
+
237
+ # must be overridden, meta tensor init is backend-specific
238
+ @classmethod
239
+ @abstractmethod
240
+ def meta_with_dtype_and_shape(cls, dtype: Any, shape: Any) -> Any:
241
+ pass
242
+
243
+ @classmethod
244
+ def from_eager(cls, t: Any) -> Any:
245
+ if type(t) is cls:
246
+ # already lazy
247
+ return t
248
+ elif isinstance(t, cls._tensor_type):
249
+ return cls(meta=cls.eager_to_meta(t), data=t)
250
+ else:
251
+ return TypeError(f"{type(t)!r} is not compatible with {cls._tensor_type!r}")
252
+
253
+
254
+ class LazyNumpyTensor(LazyBase):
255
+ _tensor_type = np.ndarray
256
+
257
+ shape: tuple[int, ...] # Makes the type checker happy in quants.py
258
+
259
+ @classmethod
260
+ def meta_with_dtype_and_shape(
261
+ cls, dtype: DTypeLike, shape: tuple[int, ...]
262
+ ) -> np.ndarray[Any, Any]:
263
+ # The initial idea was to use np.nan as the fill value,
264
+ # but non-float types like np.int16 can't use that.
265
+ # So zero it is.
266
+ cheat = np.zeros(1, dtype)
267
+ return np.lib.stride_tricks.as_strided(cheat, shape, (0 for _ in shape))
268
+
269
+ def astype(self, dtype, *args, **kwargs):
270
+ meta = type(self).meta_with_dtype_and_shape(dtype, self._meta.shape)
271
+ full_args = (
272
+ self,
273
+ dtype,
274
+ ) + args
275
+ return type(self)(
276
+ meta=meta,
277
+ args=full_args,
278
+ kwargs=kwargs,
279
+ func=(lambda a, *args, **kwargs: a.astype(*args, **kwargs)),
280
+ )
281
+
282
+ def tofile(self, *args, **kwargs):
283
+ eager = LazyNumpyTensor.to_eager(self)
284
+ return eager.tofile(*args, **kwargs)
285
+
286
+ # TODO: __array_function__
modules_forge/packages/gguf/metadata.py ADDED
@@ -0,0 +1,653 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import logging
5
+ import re
6
+ from dataclasses import dataclass
7
+ from pathlib import Path
8
+ from typing import Any, Literal, Optional
9
+
10
+ import yaml
11
+
12
+ import gguf
13
+
14
+ from .constants import Keys
15
+
16
+ logger = logging.getLogger("metadata")
17
+
18
+
19
+ @dataclass
20
+ class Metadata:
21
+ # Authorship Metadata to be written to GGUF KV Store
22
+ name: Optional[str] = None
23
+ author: Optional[str] = None
24
+ version: Optional[str] = None
25
+ organization: Optional[str] = None
26
+ finetune: Optional[str] = None
27
+ basename: Optional[str] = None
28
+ description: Optional[str] = None
29
+ quantized_by: Optional[str] = None
30
+ size_label: Optional[str] = None
31
+ url: Optional[str] = None
32
+ doi: Optional[str] = None
33
+ uuid: Optional[str] = None
34
+ repo_url: Optional[str] = None
35
+ source_url: Optional[str] = None
36
+ source_doi: Optional[str] = None
37
+ source_uuid: Optional[str] = None
38
+ source_repo_url: Optional[str] = None
39
+ license: Optional[str] = None
40
+ license_name: Optional[str] = None
41
+ license_link: Optional[str] = None
42
+ base_models: Optional[list[dict]] = None
43
+ tags: Optional[list[str]] = None
44
+ languages: Optional[list[str]] = None
45
+ datasets: Optional[list[str]] = None
46
+
47
+ @staticmethod
48
+ def load(
49
+ metadata_override_path: Optional[Path] = None,
50
+ model_path: Optional[Path] = None,
51
+ model_name: Optional[str] = None,
52
+ total_params: int = 0,
53
+ ) -> Metadata:
54
+ # This grabs as many contextual authorship metadata as possible from the model repository
55
+ # making any conversion as required to match the gguf kv store metadata format
56
+ # as well as giving users the ability to override any authorship metadata that may be incorrect
57
+
58
+ # Create a new Metadata instance
59
+ metadata = Metadata()
60
+
61
+ model_card = Metadata.load_model_card(model_path)
62
+ hf_params = Metadata.load_hf_parameters(model_path)
63
+ # TODO: load adapter_config.json when possible, it usually contains the base model of the LoRA adapter
64
+
65
+ # heuristics
66
+ metadata = Metadata.apply_metadata_heuristic(
67
+ metadata, model_card, hf_params, model_path, total_params
68
+ )
69
+
70
+ # Metadata Override File Provided
71
+ # This is based on LLM_KV_NAMES mapping in llama.cpp
72
+ metadata_override = Metadata.load_metadata_override(metadata_override_path)
73
+
74
+ metadata.name = metadata_override.get(Keys.General.NAME, metadata.name)
75
+ metadata.author = metadata_override.get(Keys.General.AUTHOR, metadata.author)
76
+ metadata.version = metadata_override.get(Keys.General.VERSION, metadata.version)
77
+ metadata.organization = metadata_override.get(
78
+ Keys.General.ORGANIZATION, metadata.organization
79
+ )
80
+
81
+ metadata.finetune = metadata_override.get(
82
+ Keys.General.FINETUNE, metadata.finetune
83
+ )
84
+ metadata.basename = metadata_override.get(
85
+ Keys.General.BASENAME, metadata.basename
86
+ )
87
+
88
+ metadata.description = metadata_override.get(
89
+ Keys.General.DESCRIPTION, metadata.description
90
+ )
91
+ metadata.quantized_by = metadata_override.get(
92
+ Keys.General.QUANTIZED_BY, metadata.quantized_by
93
+ )
94
+
95
+ metadata.size_label = metadata_override.get(
96
+ Keys.General.SIZE_LABEL, metadata.size_label
97
+ )
98
+ metadata.license_name = metadata_override.get(
99
+ Keys.General.LICENSE_NAME, metadata.license_name
100
+ )
101
+ metadata.license_link = metadata_override.get(
102
+ Keys.General.LICENSE_LINK, metadata.license_link
103
+ )
104
+
105
+ metadata.url = metadata_override.get(Keys.General.URL, metadata.url)
106
+ metadata.doi = metadata_override.get(Keys.General.DOI, metadata.doi)
107
+ metadata.uuid = metadata_override.get(Keys.General.UUID, metadata.uuid)
108
+ metadata.repo_url = metadata_override.get(
109
+ Keys.General.REPO_URL, metadata.repo_url
110
+ )
111
+
112
+ metadata.source_url = metadata_override.get(
113
+ Keys.General.SOURCE_URL, metadata.source_url
114
+ )
115
+ metadata.source_doi = metadata_override.get(
116
+ Keys.General.SOURCE_DOI, metadata.source_doi
117
+ )
118
+ metadata.source_uuid = metadata_override.get(
119
+ Keys.General.SOURCE_UUID, metadata.source_uuid
120
+ )
121
+ metadata.source_repo_url = metadata_override.get(
122
+ Keys.General.SOURCE_REPO_URL, metadata.source_repo_url
123
+ )
124
+
125
+ # Base Models is received here as an array of models
126
+ metadata.base_models = metadata_override.get(
127
+ "general.base_models", metadata.base_models
128
+ )
129
+
130
+ metadata.tags = metadata_override.get(Keys.General.TAGS, metadata.tags)
131
+ metadata.languages = metadata_override.get(
132
+ Keys.General.LANGUAGES, metadata.languages
133
+ )
134
+ metadata.datasets = metadata_override.get(
135
+ Keys.General.DATASETS, metadata.datasets
136
+ )
137
+
138
+ # Direct Metadata Override (via direct cli argument)
139
+ if model_name is not None:
140
+ metadata.name = model_name
141
+
142
+ return metadata
143
+
144
+ @staticmethod
145
+ def load_metadata_override(
146
+ metadata_override_path: Optional[Path] = None,
147
+ ) -> dict[str, Any]:
148
+ if metadata_override_path is None or not metadata_override_path.is_file():
149
+ return {}
150
+
151
+ with open(metadata_override_path, "r", encoding="utf-8") as f:
152
+ return json.load(f)
153
+
154
+ @staticmethod
155
+ def load_model_card(model_path: Optional[Path] = None) -> dict[str, Any]:
156
+ if model_path is None or not model_path.is_dir():
157
+ return {}
158
+
159
+ model_card_path = model_path / "README.md"
160
+
161
+ if not model_card_path.is_file():
162
+ return {}
163
+
164
+ # The model card metadata is assumed to always be in YAML
165
+ # ref: https://github.com/huggingface/transformers/blob/a5c642fe7a1f25d3bdcd76991443ba6ff7ee34b2/src/transformers/modelcard.py#L468-L473
166
+ with open(model_card_path, "r", encoding="utf-8") as f:
167
+ if f.readline() == "---\n":
168
+ raw = f.read().partition("---\n")[0]
169
+ data = yaml.safe_load(raw)
170
+ if isinstance(data, dict):
171
+ return data
172
+ else:
173
+ logger.error(
174
+ f"while reading YAML model card frontmatter, data is {type(data)} instead of dict"
175
+ )
176
+ return {}
177
+ else:
178
+ return {}
179
+
180
+ @staticmethod
181
+ def load_hf_parameters(model_path: Optional[Path] = None) -> dict[str, Any]:
182
+ if model_path is None or not model_path.is_dir():
183
+ return {}
184
+
185
+ config_path = model_path / "config.json"
186
+
187
+ if not config_path.is_file():
188
+ return {}
189
+
190
+ with open(config_path, "r", encoding="utf-8") as f:
191
+ return json.load(f)
192
+
193
+ @staticmethod
194
+ def id_to_title(string):
195
+ # Convert capitalization into title form unless acronym or version number
196
+ return " ".join(
197
+ [
198
+ (
199
+ w.title()
200
+ if w.islower() and not re.match(r"^(v\d+(?:\.\d+)*|\d.*)$", w)
201
+ else w
202
+ )
203
+ for w in string.strip().replace("-", " ").split()
204
+ ]
205
+ )
206
+
207
+ @staticmethod
208
+ def get_model_id_components(
209
+ model_id: Optional[str] = None, total_params: int = 0
210
+ ) -> tuple[str | None, str | None, str | None, str | None, str | None, str | None]:
211
+ # Huggingface often store model id as '<org>/<model name>'
212
+ # so let's parse it and apply some heuristics if possible for model name components
213
+
214
+ if model_id is None:
215
+ # model ID missing
216
+ return None, None, None, None, None, None
217
+
218
+ if " " in model_id:
219
+ # model ID is actually a normal human sentence
220
+ # which means its most likely a normal model name only
221
+ # not part of the hugging face naming standard, but whatever
222
+ return model_id, None, None, None, None, None
223
+
224
+ if "/" in model_id:
225
+ # model ID (huggingface style)
226
+ org_component, model_full_name_component = model_id.split("/", 1)
227
+ else:
228
+ # model ID but missing org components
229
+ org_component, model_full_name_component = None, model_id
230
+
231
+ # Check if we erroneously matched against './' or '../' etc...
232
+ if (
233
+ org_component is not None
234
+ and len(org_component) > 0
235
+ and org_component[0] == "."
236
+ ):
237
+ org_component = None
238
+
239
+ name_parts: list[str] = model_full_name_component.split("-")
240
+
241
+ # Remove empty parts
242
+ for i in reversed(range(len(name_parts))):
243
+ if len(name_parts[i]) == 0:
244
+ del name_parts[i]
245
+
246
+ name_types: list[
247
+ set[Literal["basename", "size_label", "finetune", "version", "type"]]
248
+ ] = [set() for _ in name_parts]
249
+
250
+ # Annotate the name
251
+ for i, part in enumerate(name_parts):
252
+ # Version
253
+ if re.fullmatch(r"(v|iter)?\d+([.]\d+)*", part, re.IGNORECASE):
254
+ name_types[i].add("version")
255
+ # Quant type (should not be there for base models, but still annotated)
256
+ elif re.fullmatch(r"i?q\d(_\w)*|b?fp?(16|32)", part, re.IGNORECASE):
257
+ name_types[i].add("type")
258
+ name_parts[i] = part.upper()
259
+ # Model size
260
+ elif i > 0 and re.fullmatch(
261
+ r"(([A]|\d+[x])?\d+([._]\d+)?[KMBT][\d]?|small|mini|medium|large|x?xl)",
262
+ part,
263
+ re.IGNORECASE,
264
+ ):
265
+ part = part.replace("_", ".")
266
+ # Handle weird bloom-7b1 notation
267
+ if part[-1].isdecimal():
268
+ part = part[:-2] + "." + part[-1] + part[-2]
269
+ # Normalize the size suffixes
270
+ if len(part) > 1 and part[-2].isdecimal():
271
+ if part[-1] in "kmbt":
272
+ part = part[:-1] + part[-1].upper()
273
+ if total_params != 0:
274
+ try:
275
+ label_params = float(part[:-1]) * pow(
276
+ 1000, " KMBT".find(part[-1])
277
+ )
278
+ # Only use it as a size label if it's close or bigger than the model size
279
+ # Note that LoRA adapters don't necessarily include all layers,
280
+ # so this is why bigger label sizes are accepted.
281
+ # Do not use the size label when it's smaller than 1/8 of the model size
282
+ if (
283
+ total_params < 0 and label_params < abs(total_params) // 8
284
+ ) or (
285
+ # Check both directions when the current model isn't a LoRA adapter
286
+ total_params > 0
287
+ and abs(label_params - total_params) > 7 * total_params // 8
288
+ ):
289
+ # Likely a context length
290
+ name_types[i].add("finetune")
291
+ # Lowercase the size when it's a context length
292
+ part = part[:-1] + part[-1].lower()
293
+ except ValueError:
294
+ # Failed to convert the size label to float, use it anyway
295
+ pass
296
+ if len(name_types[i]) == 0:
297
+ name_types[i].add("size_label")
298
+ name_parts[i] = part
299
+ # Some easy to recognize finetune names
300
+ elif i > 0 and re.fullmatch(
301
+ r"chat|instruct|vision|lora", part, re.IGNORECASE
302
+ ):
303
+ if total_params < 0 and part.lower() == "lora":
304
+ # ignore redundant "lora" in the finetune part when the output is a lora adapter
305
+ name_types[i].add("type")
306
+ else:
307
+ name_types[i].add("finetune")
308
+
309
+ # Ignore word-based size labels when there is at least a number-based one present
310
+ # TODO: should word-based size labels always be removed instead?
311
+ if any(
312
+ c.isdecimal()
313
+ for n, t in zip(name_parts, name_types)
314
+ if "size_label" in t
315
+ for c in n
316
+ ):
317
+ for n, t in zip(name_parts, name_types):
318
+ if "size_label" in t:
319
+ if all(c.isalpha() for c in n):
320
+ t.remove("size_label")
321
+
322
+ at_start = True
323
+ # Find the basename through the annotated name
324
+ for part, t in zip(name_parts, name_types):
325
+ if at_start and ((len(t) == 0 and part[0].isalpha()) or "version" in t):
326
+ t.add("basename")
327
+ else:
328
+ if at_start:
329
+ at_start = False
330
+ if len(t) == 0:
331
+ t.add("finetune")
332
+
333
+ # Remove the basename annotation from trailing version
334
+ for part, t in zip(reversed(name_parts), reversed(name_types)):
335
+ if "basename" in t and len(t) > 1:
336
+ t.remove("basename")
337
+ else:
338
+ break
339
+
340
+ basename = (
341
+ "-".join(n for n, t in zip(name_parts, name_types) if "basename" in t)
342
+ or None
343
+ )
344
+ # Deduplicate size labels using order-preserving 'dict' ('set' seems to sort the keys)
345
+ size_label = (
346
+ "-".join(
347
+ dict.fromkeys(
348
+ s for s, t in zip(name_parts, name_types) if "size_label" in t
349
+ ).keys()
350
+ )
351
+ or None
352
+ )
353
+ finetune = (
354
+ "-".join(f for f, t in zip(name_parts, name_types) if "finetune" in t)
355
+ or None
356
+ )
357
+ # TODO: should the basename version always be excluded?
358
+ # NOTE: multiple finetune versions are joined together
359
+ version = (
360
+ "-".join(
361
+ v
362
+ for v, t, in zip(name_parts, name_types)
363
+ if "version" in t and "basename" not in t
364
+ )
365
+ or None
366
+ )
367
+
368
+ if size_label is None and finetune is None and version is None:
369
+ # Too ambiguous, output nothing
370
+ basename = None
371
+
372
+ return (
373
+ model_full_name_component,
374
+ org_component,
375
+ basename,
376
+ finetune,
377
+ version,
378
+ size_label,
379
+ )
380
+
381
+ @staticmethod
382
+ def apply_metadata_heuristic(
383
+ metadata: Metadata,
384
+ model_card: Optional[dict] = None,
385
+ hf_params: Optional[dict] = None,
386
+ model_path: Optional[Path] = None,
387
+ total_params: int = 0,
388
+ ) -> Metadata:
389
+ # Reference Model Card Metadata: https://github.com/huggingface/hub-docs/blob/main/modelcard.md?plain=1
390
+
391
+ # Model Card Heuristics
392
+ ########################
393
+ if model_card is not None:
394
+
395
+ def use_model_card_metadata(metadata_key: str, model_card_key: str):
396
+ if (
397
+ model_card_key in model_card
398
+ and getattr(metadata, metadata_key, None) is None
399
+ ):
400
+ setattr(metadata, metadata_key, model_card.get(model_card_key))
401
+
402
+ def use_array_model_card_metadata(metadata_key: str, model_card_key: str):
403
+ # Note: Will append rather than replace if already exist
404
+ tags_value = model_card.get(model_card_key, None)
405
+ if tags_value is None:
406
+ return
407
+
408
+ current_value = getattr(metadata, metadata_key, None)
409
+ if current_value is None:
410
+ current_value = []
411
+
412
+ if isinstance(tags_value, str):
413
+ current_value.append(tags_value)
414
+ elif isinstance(tags_value, list):
415
+ current_value.extend(tags_value)
416
+
417
+ setattr(metadata, metadata_key, current_value)
418
+
419
+ # LLAMA.cpp's direct internal convention
420
+ # (Definitely not part of hugging face formal/informal standard)
421
+ #########################################
422
+ use_model_card_metadata("name", "name")
423
+ use_model_card_metadata("author", "author")
424
+ use_model_card_metadata("version", "version")
425
+ use_model_card_metadata("organization", "organization")
426
+ use_model_card_metadata("description", "description")
427
+ use_model_card_metadata("finetune", "finetune")
428
+ use_model_card_metadata("basename", "basename")
429
+ use_model_card_metadata("size_label", "size_label")
430
+ use_model_card_metadata("source_url", "url")
431
+ use_model_card_metadata("source_doi", "doi")
432
+ use_model_card_metadata("source_uuid", "uuid")
433
+ use_model_card_metadata("source_repo_url", "repo_url")
434
+
435
+ # LLAMA.cpp's huggingface style convention
436
+ # (Definitely not part of hugging face formal/informal standard... but with model_ appended to match their style)
437
+ ###########################################
438
+ use_model_card_metadata("name", "model_name")
439
+ use_model_card_metadata("author", "model_author")
440
+ use_model_card_metadata("version", "model_version")
441
+ use_model_card_metadata("organization", "model_organization")
442
+ use_model_card_metadata("description", "model_description")
443
+ use_model_card_metadata("finetune", "model_finetune")
444
+ use_model_card_metadata("basename", "model_basename")
445
+ use_model_card_metadata("size_label", "model_size_label")
446
+ use_model_card_metadata("source_url", "model_url")
447
+ use_model_card_metadata("source_doi", "model_doi")
448
+ use_model_card_metadata("source_uuid", "model_uuid")
449
+ use_model_card_metadata("source_repo_url", "model_repo_url")
450
+
451
+ # Hugging Face Direct Convention
452
+ #################################
453
+
454
+ # Not part of huggingface model card standard but notice some model creator using it
455
+ # such as TheBloke in 'TheBloke/Mistral-7B-Instruct-v0.2-GGUF'
456
+ use_model_card_metadata("name", "model_name")
457
+ use_model_card_metadata("author", "model_creator")
458
+ use_model_card_metadata("basename", "model_type")
459
+
460
+ if "base_model" in model_card:
461
+ # This represents the parent models that this is based on
462
+ # Example: stabilityai/stable-diffusion-xl-base-1.0. Can also be a list (for merges)
463
+ # Example of merges: https://huggingface.co/EmbeddedLLM/Mistral-7B-Merge-14-v0.1/blob/main/README.md
464
+ metadata_base_models = []
465
+ base_model_value = model_card.get("base_model", None)
466
+
467
+ if base_model_value is not None:
468
+ if isinstance(base_model_value, str):
469
+ metadata_base_models.append(base_model_value)
470
+ elif isinstance(base_model_value, list):
471
+ metadata_base_models.extend(base_model_value)
472
+
473
+ if metadata.base_models is None:
474
+ metadata.base_models = []
475
+
476
+ for model_id in metadata_base_models:
477
+ # NOTE: model size of base model is assumed to be similar to the size of the current model
478
+ (
479
+ model_full_name_component,
480
+ org_component,
481
+ basename,
482
+ finetune,
483
+ version,
484
+ size_label,
485
+ ) = Metadata.get_model_id_components(model_id, total_params)
486
+ base_model = {}
487
+ if model_full_name_component is not None:
488
+ base_model["name"] = Metadata.id_to_title(
489
+ model_full_name_component
490
+ )
491
+ if org_component is not None:
492
+ base_model["organization"] = Metadata.id_to_title(org_component)
493
+ if version is not None:
494
+ base_model["version"] = version
495
+ if (
496
+ org_component is not None
497
+ and model_full_name_component is not None
498
+ ):
499
+ base_model["repo_url"] = (
500
+ f"https://huggingface.co/{org_component}/{model_full_name_component}"
501
+ )
502
+ metadata.base_models.append(base_model)
503
+
504
+ use_model_card_metadata("license", "license")
505
+ use_model_card_metadata("license_name", "license_name")
506
+ use_model_card_metadata("license_link", "license_link")
507
+
508
+ use_array_model_card_metadata("tags", "tags")
509
+ use_array_model_card_metadata("tags", "pipeline_tag")
510
+
511
+ use_array_model_card_metadata("languages", "languages")
512
+ use_array_model_card_metadata("languages", "language")
513
+
514
+ use_array_model_card_metadata("datasets", "datasets")
515
+ use_array_model_card_metadata("datasets", "dataset")
516
+
517
+ # Hugging Face Parameter Heuristics
518
+ ####################################
519
+
520
+ if hf_params is not None:
521
+
522
+ hf_name_or_path = hf_params.get("_name_or_path")
523
+ if hf_name_or_path is not None and hf_name_or_path.count("/") <= 1:
524
+ # Use _name_or_path only if its actually a model name and not some computer path
525
+ # e.g. 'meta-llama/Llama-2-7b-hf'
526
+ model_id = hf_name_or_path
527
+ (
528
+ model_full_name_component,
529
+ org_component,
530
+ basename,
531
+ finetune,
532
+ version,
533
+ size_label,
534
+ ) = Metadata.get_model_id_components(model_id, total_params)
535
+ if metadata.name is None and model_full_name_component is not None:
536
+ metadata.name = Metadata.id_to_title(model_full_name_component)
537
+ if metadata.organization is None and org_component is not None:
538
+ metadata.organization = Metadata.id_to_title(org_component)
539
+ if metadata.basename is None and basename is not None:
540
+ metadata.basename = basename
541
+ if metadata.finetune is None and finetune is not None:
542
+ metadata.finetune = finetune
543
+ if metadata.version is None and version is not None:
544
+ metadata.version = version
545
+ if metadata.size_label is None and size_label is not None:
546
+ metadata.size_label = size_label
547
+
548
+ # Directory Folder Name Fallback Heuristics
549
+ ############################################
550
+ if model_path is not None:
551
+ model_id = model_path.name
552
+ (
553
+ model_full_name_component,
554
+ org_component,
555
+ basename,
556
+ finetune,
557
+ version,
558
+ size_label,
559
+ ) = Metadata.get_model_id_components(model_id, total_params)
560
+ if metadata.name is None and model_full_name_component is not None:
561
+ metadata.name = Metadata.id_to_title(model_full_name_component)
562
+ if metadata.organization is None and org_component is not None:
563
+ metadata.organization = Metadata.id_to_title(org_component)
564
+ if metadata.basename is None and basename is not None:
565
+ metadata.basename = basename
566
+ if metadata.finetune is None and finetune is not None:
567
+ metadata.finetune = finetune
568
+ if metadata.version is None and version is not None:
569
+ metadata.version = version
570
+ if metadata.size_label is None and size_label is not None:
571
+ metadata.size_label = size_label
572
+
573
+ return metadata
574
+
575
+ def set_gguf_meta_model(self, gguf_writer: gguf.GGUFWriter):
576
+ assert self.name is not None
577
+ gguf_writer.add_name(self.name)
578
+
579
+ if self.author is not None:
580
+ gguf_writer.add_author(self.author)
581
+ if self.version is not None:
582
+ gguf_writer.add_version(self.version)
583
+ if self.organization is not None:
584
+ gguf_writer.add_organization(self.organization)
585
+
586
+ if self.finetune is not None:
587
+ gguf_writer.add_finetune(self.finetune)
588
+ if self.basename is not None:
589
+ gguf_writer.add_basename(self.basename)
590
+
591
+ if self.description is not None:
592
+ gguf_writer.add_description(self.description)
593
+ if self.quantized_by is not None:
594
+ gguf_writer.add_quantized_by(self.quantized_by)
595
+
596
+ if self.size_label is not None:
597
+ gguf_writer.add_size_label(self.size_label)
598
+
599
+ if self.license is not None:
600
+ gguf_writer.add_license(self.license)
601
+ if self.license_name is not None:
602
+ gguf_writer.add_license_name(self.license_name)
603
+ if self.license_link is not None:
604
+ gguf_writer.add_license_link(self.license_link)
605
+
606
+ if self.url is not None:
607
+ gguf_writer.add_url(self.url)
608
+ if self.doi is not None:
609
+ gguf_writer.add_doi(self.doi)
610
+ if self.uuid is not None:
611
+ gguf_writer.add_uuid(self.uuid)
612
+ if self.repo_url is not None:
613
+ gguf_writer.add_repo_url(self.repo_url)
614
+
615
+ if self.source_url is not None:
616
+ gguf_writer.add_source_url(self.source_url)
617
+ if self.source_doi is not None:
618
+ gguf_writer.add_source_doi(self.source_doi)
619
+ if self.source_uuid is not None:
620
+ gguf_writer.add_source_uuid(self.source_uuid)
621
+ if self.source_repo_url is not None:
622
+ gguf_writer.add_source_repo_url(self.source_repo_url)
623
+
624
+ if self.base_models is not None:
625
+ gguf_writer.add_base_model_count(len(self.base_models))
626
+ for key, base_model_entry in enumerate(self.base_models):
627
+ if "name" in base_model_entry:
628
+ gguf_writer.add_base_model_name(key, base_model_entry["name"])
629
+ if "author" in base_model_entry:
630
+ gguf_writer.add_base_model_author(key, base_model_entry["author"])
631
+ if "version" in base_model_entry:
632
+ gguf_writer.add_base_model_version(key, base_model_entry["version"])
633
+ if "organization" in base_model_entry:
634
+ gguf_writer.add_base_model_organization(
635
+ key, base_model_entry["organization"]
636
+ )
637
+ if "url" in base_model_entry:
638
+ gguf_writer.add_base_model_url(key, base_model_entry["url"])
639
+ if "doi" in base_model_entry:
640
+ gguf_writer.add_base_model_doi(key, base_model_entry["doi"])
641
+ if "uuid" in base_model_entry:
642
+ gguf_writer.add_base_model_uuid(key, base_model_entry["uuid"])
643
+ if "repo_url" in base_model_entry:
644
+ gguf_writer.add_base_model_repo_url(
645
+ key, base_model_entry["repo_url"]
646
+ )
647
+
648
+ if self.tags is not None:
649
+ gguf_writer.add_tags(self.tags)
650
+ if self.languages is not None:
651
+ gguf_writer.add_languages(self.languages)
652
+ if self.datasets is not None:
653
+ gguf_writer.add_datasets(self.datasets)
modules_forge/packages/gguf/quants.py ADDED
@@ -0,0 +1,1762 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from abc import ABC, abstractmethod
4
+ from math import ceil, log2
5
+ from typing import Any, Callable, Sequence
6
+
7
+ import numpy as np
8
+ import torch
9
+ from numpy.typing import DTypeLike
10
+
11
+ from .constants import GGML_QUANT_SIZES, QK_K, GGMLQuantizationType
12
+ from .lazy import LazyNumpyTensor
13
+ from .quick_4bits_ops import (
14
+ change_4bits_order,
15
+ quick_unpack_4bits,
16
+ quick_unpack_4bits_u,
17
+ )
18
+
19
+ quick_split = lambda x, p: torch.split(x, p + [x.shape[1] - sum(p)], dim=-1)
20
+
21
+
22
+ def quant_shape_to_byte_shape(
23
+ shape: Sequence[int], quant_type: GGMLQuantizationType
24
+ ) -> tuple[int, ...]:
25
+ block_size, type_size = GGML_QUANT_SIZES[quant_type]
26
+ if shape[-1] % block_size != 0:
27
+ raise ValueError(
28
+ f"Quantized tensor row size ({shape[-1]}) is not a multiple of {quant_type.name} block size ({block_size})"
29
+ )
30
+ return (*shape[:-1], shape[-1] // block_size * type_size)
31
+
32
+
33
+ def quant_shape_from_byte_shape(
34
+ shape: Sequence[int], quant_type: GGMLQuantizationType
35
+ ) -> tuple[int, ...]:
36
+ block_size, type_size = GGML_QUANT_SIZES[quant_type]
37
+ if shape[-1] % type_size != 0:
38
+ raise ValueError(
39
+ f"Quantized tensor bytes per row ({shape[-1]}) is not a multiple of {quant_type.name} type size ({type_size})"
40
+ )
41
+ return (*shape[:-1], shape[-1] // type_size * block_size)
42
+
43
+
44
+ # This is faster than np.vectorize and np.apply_along_axis because it works on more than one row at a time
45
+ def _apply_over_grouped_rows(
46
+ func: Callable[[np.ndarray], np.ndarray],
47
+ arr: np.ndarray,
48
+ otype: DTypeLike,
49
+ oshape: tuple[int, ...],
50
+ ) -> np.ndarray:
51
+ rows = arr.reshape((-1, arr.shape[-1]))
52
+ osize = 1
53
+ for dim in oshape:
54
+ osize *= dim
55
+ out = np.empty(shape=osize, dtype=otype)
56
+ # compute over groups of 16 rows (arbitrary, but seems good for performance)
57
+ n_groups = (rows.shape[0] // 16) or 1
58
+ np.concatenate(
59
+ [func(group).ravel() for group in np.array_split(rows, n_groups)],
60
+ axis=0,
61
+ out=out,
62
+ )
63
+ return out.reshape(oshape)
64
+
65
+
66
+ # round away from zero
67
+ # ref: https://stackoverflow.com/a/59143326/22827863
68
+ def np_roundf(n: np.ndarray) -> np.ndarray:
69
+ a = abs(n)
70
+ floored = np.floor(a)
71
+ b = floored + np.floor(2 * (a - floored))
72
+ return np.sign(n) * b
73
+
74
+
75
+ class QuantError(Exception): ...
76
+
77
+
78
+ _type_traits: dict[GGMLQuantizationType, type[__Quant]] = {}
79
+
80
+
81
+ def quantize(data: np.ndarray, qtype: GGMLQuantizationType) -> np.ndarray:
82
+ if qtype == GGMLQuantizationType.F32:
83
+ return data.astype(np.float32, copy=False)
84
+ elif qtype == GGMLQuantizationType.F16:
85
+ return data.astype(np.float16, copy=False)
86
+ elif (q := _type_traits.get(qtype)) is not None:
87
+ return q.quantize(data)
88
+ else:
89
+ raise NotImplementedError(
90
+ f"Quantization for {qtype.name} is not yet implemented"
91
+ )
92
+
93
+
94
+ def dequantize(data: np.ndarray, qtype: GGMLQuantizationType) -> np.ndarray:
95
+ if qtype == GGMLQuantizationType.F32:
96
+ return data.view(np.float32)
97
+ elif qtype == GGMLQuantizationType.F16:
98
+ return data.view(np.float16).astype(np.float32)
99
+ elif (q := _type_traits.get(qtype)) is not None:
100
+ return q.dequantize(data)
101
+ else:
102
+ raise NotImplementedError(
103
+ f"Dequantization for {qtype.name} is not yet implemented"
104
+ )
105
+
106
+
107
+ class __Quant(ABC):
108
+ qtype: GGMLQuantizationType
109
+ block_size: int
110
+ type_size: int
111
+
112
+ grid: np.ndarray[Any, np.dtype[np.float32]] | None = None
113
+ grid_shape: tuple[int, int] = (0, 0)
114
+ grid_map: tuple[int | float, ...] = ()
115
+ grid_hex: bytes | None = None
116
+
117
+ def __init__(self):
118
+ return TypeError("Quant conversion classes can't have instances")
119
+
120
+ def __init_subclass__(cls, qtype: GGMLQuantizationType) -> None:
121
+ cls.qtype = qtype
122
+ cls.block_size, cls.type_size = GGML_QUANT_SIZES[qtype]
123
+ cls.__quantize_lazy = LazyNumpyTensor._wrap_fn(
124
+ cls.__quantize_array, meta_noop=(np.uint8, cls.__shape_to_bytes)
125
+ )
126
+ cls.__dequantize_lazy = LazyNumpyTensor._wrap_fn(
127
+ cls.__dequantize_array, meta_noop=(np.float32, cls.__shape_from_bytes)
128
+ )
129
+ assert qtype not in _type_traits
130
+ _type_traits[qtype] = cls
131
+
132
+ @classmethod
133
+ def init_grid(cls):
134
+ if cls.grid is not None or cls.grid_hex is None:
135
+ return
136
+
137
+ bits_per_elem = ceil(log2(len(cls.grid_map)))
138
+ assert bits_per_elem != 0, cls.qtype.name
139
+ elems_per_byte = 8 // bits_per_elem
140
+
141
+ grid = np.frombuffer(cls.grid_hex, dtype=np.uint8)
142
+ # decode hexadecimal chars from grid
143
+ grid = grid.reshape((-1, 2))
144
+ grid = (np.where(grid > 0x40, grid + 9, grid) & 0x0F) << np.array(
145
+ [4, 0], dtype=np.uint8
146
+ ).reshape((1, 2))
147
+ grid = grid[..., 0] | grid[..., 1]
148
+ # unpack the grid values
149
+ grid = grid.reshape((-1, 1)) >> np.array(
150
+ [i for i in range(0, 8, 8 // elems_per_byte)], dtype=np.uint8
151
+ ).reshape((1, elems_per_byte))
152
+ grid = (grid & ((1 << bits_per_elem) - 1)).reshape((-1, 1))
153
+ grid_map = np.array(cls.grid_map, dtype=np.float32).reshape((1, -1))
154
+ grid = np.take_along_axis(grid_map, grid, axis=-1)
155
+ cls.grid = grid.reshape((1, 1, *cls.grid_shape))
156
+
157
+ @classmethod
158
+ def quantize_pytorch(cls, data, parent) -> torch.Tensor:
159
+ if not parent.baked:
160
+ raise ValueError("GGUF Tensor is not baked!")
161
+
162
+ block_size, type_size = GGML_QUANT_SIZES[cls.qtype]
163
+ blocks = data.reshape(-1, block_size)
164
+ parent.data = cls.quantize_blocks_pytorch(
165
+ blocks, block_size, type_size, parent
166
+ ).contiguous()
167
+ return parent
168
+
169
+ @classmethod
170
+ def bake(cls, parameter):
171
+ if parameter.baked:
172
+ return
173
+
174
+ data = parameter.data
175
+ cls.block_size, cls.type_size = GGML_QUANT_SIZES[cls.qtype]
176
+ rows = data.reshape((-1, data.shape[-1])).view(torch.uint8)
177
+ n_blocks = rows.numel() // cls.type_size
178
+ blocks = rows.reshape((n_blocks, cls.type_size))
179
+ parameter.data = blocks.contiguous()
180
+ cls.bake_inner(parameter)
181
+ parameter.baked = True
182
+ return
183
+
184
+ @classmethod
185
+ def bake_inner(cls, parameter):
186
+ pass
187
+
188
+ @classmethod
189
+ def dequantize_pytorch(cls, x):
190
+ if not x.baked:
191
+ raise ValueError("GGUF Tensor is not baked!")
192
+
193
+ blocks = cls.dequantize_blocks_pytorch(x.data, cls.block_size, cls.type_size, x)
194
+ return blocks.view(x.shape)
195
+
196
+ @classmethod
197
+ @abstractmethod
198
+ def dequantize_blocks_pytorch(
199
+ cls, blocks, block_size, type_size, parameter
200
+ ) -> torch.Tensor:
201
+ raise NotImplementedError
202
+
203
+ @classmethod
204
+ @abstractmethod
205
+ def quantize_blocks_pytorch(
206
+ cls, blocks, block_size, type_size, parent
207
+ ) -> torch.Tensor:
208
+ raise NotImplementedError(
209
+ 'Low bit LoRA for this data type is not implemented yet. Please select "Automatic (fp16 LoRA)" in "Diffusion in Low Bits" (on the top line of this page) to use this LoRA.'
210
+ )
211
+
212
+ @classmethod
213
+ @abstractmethod
214
+ def quantize_blocks(cls, blocks: np.ndarray) -> np.ndarray:
215
+ raise NotImplementedError
216
+
217
+ @classmethod
218
+ @abstractmethod
219
+ def dequantize_blocks(cls, blocks: np.ndarray) -> np.ndarray:
220
+ raise NotImplementedError
221
+
222
+ @classmethod
223
+ def quantize_rows(cls, rows: np.ndarray) -> np.ndarray:
224
+ rows = rows.astype(np.float32, copy=False)
225
+ shape = rows.shape
226
+ n_blocks = rows.size // cls.block_size
227
+ blocks = rows.reshape((n_blocks, cls.block_size))
228
+ blocks = cls.quantize_blocks(blocks)
229
+ assert blocks.dtype == np.uint8
230
+ assert blocks.shape[-1] == cls.type_size
231
+ return blocks.reshape(cls.__shape_to_bytes(shape))
232
+
233
+ @classmethod
234
+ def dequantize_rows(cls, rows: np.ndarray) -> np.ndarray:
235
+ rows = rows.view(np.uint8)
236
+ shape = rows.shape
237
+ n_blocks = rows.size // cls.type_size
238
+ blocks = rows.reshape((n_blocks, cls.type_size))
239
+ blocks = cls.dequantize_blocks(blocks)
240
+ assert blocks.dtype == np.float32
241
+ assert blocks.shape[-1] == cls.block_size
242
+ return blocks.reshape(cls.__shape_from_bytes(shape))
243
+
244
+ @classmethod
245
+ def __shape_to_bytes(cls, shape: Sequence[int]):
246
+ return quant_shape_to_byte_shape(shape, cls.qtype)
247
+
248
+ @classmethod
249
+ def __shape_from_bytes(cls, shape: Sequence[int]):
250
+ return quant_shape_from_byte_shape(shape, cls.qtype)
251
+
252
+ @classmethod
253
+ def __quantize_array(cls, array: np.ndarray) -> np.ndarray:
254
+ return _apply_over_grouped_rows(
255
+ cls.quantize_rows,
256
+ arr=array,
257
+ otype=np.uint8,
258
+ oshape=cls.__shape_to_bytes(array.shape),
259
+ )
260
+
261
+ @classmethod
262
+ def __dequantize_array(cls, array: np.ndarray) -> np.ndarray:
263
+ cls.init_grid()
264
+ return _apply_over_grouped_rows(
265
+ cls.dequantize_rows,
266
+ arr=array,
267
+ otype=np.float32,
268
+ oshape=cls.__shape_from_bytes(array.shape),
269
+ )
270
+
271
+ @classmethod
272
+ def __quantize_lazy(cls, lazy_tensor: LazyNumpyTensor, /) -> Any:
273
+ pass
274
+
275
+ @classmethod
276
+ def __dequantize_lazy(cls, lazy_tensor: LazyNumpyTensor, /) -> Any:
277
+ pass
278
+
279
+ @classmethod
280
+ def can_quantize(cls, tensor: np.ndarray | LazyNumpyTensor) -> bool:
281
+ return tensor.shape[-1] % cls.block_size == 0
282
+
283
+ @classmethod
284
+ def quantize(cls, tensor: np.ndarray | LazyNumpyTensor) -> np.ndarray:
285
+ if not cls.can_quantize(tensor):
286
+ raise QuantError(
287
+ f"Can't quantize tensor with shape {tensor.shape} to {cls.qtype.name}"
288
+ )
289
+ if isinstance(tensor, LazyNumpyTensor):
290
+ return cls.__quantize_lazy(tensor)
291
+ else:
292
+ return cls.__quantize_array(tensor)
293
+
294
+ @classmethod
295
+ def dequantize(cls, tensor: np.ndarray | LazyNumpyTensor) -> np.ndarray:
296
+ if isinstance(tensor, LazyNumpyTensor):
297
+ return cls.__dequantize_lazy(tensor)
298
+ else:
299
+ return cls.__dequantize_array(tensor)
300
+
301
+
302
+ class BF16(__Quant, qtype=GGMLQuantizationType.BF16):
303
+ @classmethod
304
+ # same as ggml_compute_fp32_to_bf16 in ggml-impl.h
305
+ def quantize_blocks(cls, blocks: np.ndarray) -> np.ndarray:
306
+ n = blocks.view(np.uint32)
307
+ # force nan to quiet
308
+ n = np.where(
309
+ (n & 0x7FFFFFFF) > 0x7F800000,
310
+ (n & np.uint32(0xFFFF0000)) | np.uint32(64 << 16),
311
+ n,
312
+ )
313
+ # round to nearest even
314
+ n = (np.uint64(n) + (0x7FFF + ((n >> 16) & 1))) >> 16
315
+ return n.astype(np.uint16).view(np.uint8)
316
+
317
+ @classmethod
318
+ def dequantize_blocks(cls, blocks: np.ndarray) -> np.ndarray:
319
+ return (blocks.view(np.int16).astype(np.int32) << 16).view(np.float32)
320
+
321
+ @classmethod
322
+ def dequantize_blocks_pytorch(
323
+ cls, blocks, block_size, type_size, parameter
324
+ ) -> torch.Tensor:
325
+ return (blocks.view(torch.int16).to(torch.int32) << 16).view(torch.float32)
326
+
327
+
328
+ class Q4_0(__Quant, qtype=GGMLQuantizationType.Q4_0):
329
+ @classmethod
330
+ def quantize_blocks(cls, blocks: np.ndarray) -> np.ndarray:
331
+ n_blocks = blocks.shape[0]
332
+
333
+ imax = abs(blocks).argmax(axis=-1, keepdims=True)
334
+ max = np.take_along_axis(blocks, imax, axis=-1)
335
+
336
+ d = max / -8
337
+ with np.errstate(divide="ignore"):
338
+ id = np.where(d == 0, 0, 1 / d)
339
+ # FIXME: Q4_0's reference rounding is cursed and depends on FMA
340
+ qs = (
341
+ np.trunc(
342
+ (np.float64(blocks) * np.float64(id)) + np.float64(8.5),
343
+ dtype=np.float32,
344
+ )
345
+ .astype(np.uint8)
346
+ .clip(0, 15)
347
+ )
348
+
349
+ qs = qs.reshape((n_blocks, 2, cls.block_size // 2))
350
+ qs = qs[..., 0, :] | (qs[..., 1, :] << np.uint8(4))
351
+
352
+ d = d.astype(np.float16).view(np.uint8)
353
+
354
+ return np.concatenate([d, qs], axis=-1)
355
+
356
+ @classmethod
357
+ def dequantize_blocks(cls, blocks: np.ndarray) -> np.ndarray:
358
+ n_blocks = blocks.shape[0]
359
+
360
+ d, qs = np.hsplit(blocks, [2])
361
+
362
+ d = d.view(np.float16).astype(np.float32)
363
+
364
+ qs = qs.reshape((n_blocks, -1, 1, cls.block_size // 2)) >> np.array(
365
+ [0, 4], dtype=np.uint8
366
+ ).reshape((1, 1, 2, 1))
367
+ qs = (qs & np.uint8(0x0F)).reshape((n_blocks, -1)).astype(np.int8) - np.int8(8)
368
+
369
+ return d * qs.astype(np.float32)
370
+
371
+ @classmethod
372
+ def bake_inner(cls, parameter):
373
+ blocks = parameter.data
374
+ d, x = quick_split(blocks, [2])
375
+ d = d.view(torch.float16).to(parameter.computation_dtype).view(torch.uint8)
376
+ x = change_4bits_order(x).view(torch.uint8)
377
+ parameter.data = torch.cat([d, x], dim=-1).contiguous()
378
+ return
379
+
380
+ @classmethod
381
+ def dequantize_blocks_pytorch(
382
+ cls, blocks, block_size, type_size, parameter
383
+ ) -> torch.Tensor:
384
+ d, qs = quick_split(blocks, [2])
385
+ d = d.view(parameter.computation_dtype)
386
+ qs = quick_unpack_4bits(qs)
387
+ return d * qs
388
+
389
+ @classmethod
390
+ def quantize_blocks_pytorch(
391
+ cls, blocks, block_size, type_size, parent
392
+ ) -> torch.Tensor:
393
+ # Copyright Forge 2024, AGPL V3 + CC-BY SA
394
+
395
+ n_blocks = blocks.shape[0]
396
+
397
+ imax = torch.abs(blocks).argmax(dim=-1, keepdim=True)
398
+ max_vals = torch.gather(blocks, -1, imax)
399
+
400
+ d = max_vals / -8
401
+ id = torch.where(d == 0, torch.tensor(0.0, device=d.device), 1.0 / d)
402
+
403
+ qs = torch.trunc((blocks * id) + 8.5).clip(0, 15).to(torch.uint8)
404
+
405
+ qs = qs.reshape((n_blocks, block_size // 2, 2))
406
+ qs = qs[..., 0] | (qs[..., 1] << 4)
407
+
408
+ d = d.to(parent.computation_dtype).view(torch.uint8)
409
+
410
+ return torch.cat([d, qs], dim=-1)
411
+
412
+
413
+ class Q4_1(__Quant, qtype=GGMLQuantizationType.Q4_1):
414
+ @classmethod
415
+ def quantize_blocks(cls, blocks: np.ndarray) -> np.ndarray:
416
+ n_blocks = blocks.shape[0]
417
+
418
+ max = blocks.max(axis=-1, keepdims=True)
419
+ min = blocks.min(axis=-1, keepdims=True)
420
+
421
+ d = (max - min) / 15
422
+ with np.errstate(divide="ignore"):
423
+ id = np.where(d == 0, 0, 1 / d)
424
+ qs = (
425
+ np.trunc((blocks - min) * id + np.float32(0.5), dtype=np.float32)
426
+ .astype(np.uint8)
427
+ .clip(0, 15)
428
+ )
429
+
430
+ qs = qs.reshape((n_blocks, 2, cls.block_size // 2))
431
+ qs = qs[..., 0, :] | (qs[..., 1, :] << np.uint8(4))
432
+
433
+ d = d.astype(np.float16).view(np.uint8)
434
+ m = min.astype(np.float16).view(np.uint8)
435
+
436
+ return np.concatenate([d, m, qs], axis=-1)
437
+
438
+ @classmethod
439
+ def dequantize_blocks(cls, blocks: np.ndarray) -> np.ndarray:
440
+ n_blocks = blocks.shape[0]
441
+
442
+ d, rest = np.hsplit(blocks, [2])
443
+ m, qs = np.hsplit(rest, [2])
444
+
445
+ d = d.view(np.float16).astype(np.float32)
446
+ m = m.view(np.float16).astype(np.float32)
447
+
448
+ qs = qs.reshape((n_blocks, -1, 1, cls.block_size // 2)) >> np.array(
449
+ [0, 4], dtype=np.uint8
450
+ ).reshape((1, 1, 2, 1))
451
+ qs = (qs & np.uint8(0x0F)).reshape((n_blocks, -1)).astype(np.float32)
452
+
453
+ return (d * qs) + m
454
+
455
+ @classmethod
456
+ def bake_inner(cls, parameter):
457
+ blocks = parameter.data
458
+
459
+ d, m, qs = quick_split(blocks, [2, 2])
460
+ d = d.view(torch.float16).to(parameter.computation_dtype).view(torch.uint8)
461
+ m = m.view(torch.float16).to(parameter.computation_dtype).view(torch.uint8)
462
+ qs = change_4bits_order(qs).view(torch.uint8)
463
+
464
+ parameter.data = torch.cat([d, m, qs], dim=-1).contiguous()
465
+
466
+ return
467
+
468
+ @classmethod
469
+ def dequantize_blocks_pytorch(
470
+ cls, blocks, block_size, type_size, parameter
471
+ ) -> torch.Tensor:
472
+ d, m, qs = quick_split(blocks, [2, 2])
473
+ d = d.view(parameter.computation_dtype)
474
+ m = m.view(parameter.computation_dtype)
475
+ qs = quick_unpack_4bits_u(qs)
476
+ return (d * qs) + m
477
+
478
+
479
+ class Q5_0(__Quant, qtype=GGMLQuantizationType.Q5_0):
480
+ @classmethod
481
+ def quantize_blocks(cls, blocks: np.ndarray) -> np.ndarray:
482
+ n_blocks = blocks.shape[0]
483
+
484
+ imax = abs(blocks).argmax(axis=-1, keepdims=True)
485
+ max = np.take_along_axis(blocks, imax, axis=-1)
486
+
487
+ d = max / -16
488
+ with np.errstate(divide="ignore"):
489
+ id = np.where(d == 0, 0, 1 / d)
490
+ # FIXME: Q5_0's reference rounding is cursed and depends on FMA
491
+ q = (
492
+ np.trunc(
493
+ (np.float64(blocks) * np.float64(id)) + np.float64(16.5),
494
+ dtype=np.float32,
495
+ )
496
+ .astype(np.uint8)
497
+ .clip(0, 31)
498
+ )
499
+
500
+ qs = q.reshape((n_blocks, 2, cls.block_size // 2))
501
+ qs = (qs[..., 0, :] & np.uint8(0x0F)) | (qs[..., 1, :] << np.uint8(4))
502
+
503
+ qh = np.packbits(
504
+ q.reshape((n_blocks, 1, 32)) >> np.uint8(4), axis=-1, bitorder="little"
505
+ ).reshape(n_blocks, 4)
506
+
507
+ d = d.astype(np.float16).view(np.uint8)
508
+
509
+ return np.concatenate([d, qh, qs], axis=-1)
510
+
511
+ @classmethod
512
+ def dequantize_blocks(cls, blocks: np.ndarray) -> np.ndarray:
513
+ n_blocks = blocks.shape[0]
514
+
515
+ d, rest = np.hsplit(blocks, [2])
516
+ qh, qs = np.hsplit(rest, [4])
517
+
518
+ d = d.view(np.float16).astype(np.float32)
519
+ qh = qh.view(np.uint32)
520
+
521
+ qh = qh.reshape((n_blocks, 1)) >> np.array(
522
+ [i for i in range(32)], dtype=np.uint32
523
+ ).reshape((1, 32))
524
+ ql = qs.reshape((n_blocks, -1, 1, cls.block_size // 2)) >> np.array(
525
+ [0, 4], dtype=np.uint8
526
+ ).reshape((1, 1, 2, 1))
527
+ qh = (qh & np.uint32(0x01)).astype(np.uint8)
528
+ ql = (ql & np.uint8(0x0F)).reshape((n_blocks, -1))
529
+
530
+ qs = (ql | (qh << np.uint8(4))).astype(np.int8) - np.int8(16)
531
+
532
+ return d * qs.astype(np.float32)
533
+
534
+ @classmethod
535
+ def dequantize_blocks_pytorch(
536
+ cls, blocks, block_size, type_size, parameter
537
+ ) -> torch.Tensor:
538
+ def to_uint32(x):
539
+ # pytorch uint32 by City96 - Apache-2.0
540
+ x = x.view(torch.uint8).to(torch.int32)
541
+ return (x[:, 0] | x[:, 1] << 8 | x[:, 2] << 16 | x[:, 3] << 24).unsqueeze(1)
542
+
543
+ n_blocks = blocks.shape[0]
544
+
545
+ d, qh, qs = quick_split(blocks, [2, 4])
546
+ d = d.view(torch.float16).to(parameter.computation_dtype)
547
+ qh = to_uint32(qh)
548
+
549
+ qh = qh.reshape(n_blocks, 1) >> torch.arange(
550
+ 32, device=d.device, dtype=torch.int32
551
+ ).reshape(1, 32)
552
+ ql = qs.reshape(n_blocks, -1, 1, block_size // 2) >> torch.tensor(
553
+ [0, 4], device=d.device, dtype=torch.uint8
554
+ ).reshape(1, 1, 2, 1)
555
+
556
+ qh = (qh & 1).to(torch.uint8)
557
+ ql = (ql & 0x0F).reshape(n_blocks, -1)
558
+
559
+ qs = (ql | (qh << 4)).to(torch.int8) - 16
560
+ return d * qs
561
+
562
+ @classmethod
563
+ def quantize_blocks_pytorch(
564
+ cls, blocks, block_size, type_size, parent
565
+ ) -> torch.Tensor:
566
+ # Copyright Forge 2024, AGPL V3 + CC-BY SA
567
+
568
+ n_blocks = blocks.shape[0]
569
+
570
+ imax = torch.abs(blocks).argmax(dim=-1, keepdim=True)
571
+ max_val = torch.gather(blocks, dim=-1, index=imax)
572
+
573
+ d = max_val / -16
574
+ id = torch.where(d == 0, torch.tensor(0.0, device=d.device), 1.0 / d)
575
+
576
+ q = (
577
+ torch.trunc((blocks.float() * id.float()) + 16.5)
578
+ .clamp(0, 31)
579
+ .to(torch.uint8)
580
+ )
581
+
582
+ qs = q.view(n_blocks, 2, block_size // 2)
583
+ qs = (qs[..., 0, :] & 0x0F) | (qs[..., 1, :] << 4)
584
+
585
+ qh = q.view(n_blocks, 32)
586
+ qh_packed = torch.zeros((n_blocks, 4), dtype=torch.uint8, device=qh.device)
587
+
588
+ for i in range(4):
589
+ qh_packed[:, i] = (
590
+ (qh[:, i * 8 + 0] >> 4)
591
+ | (qh[:, i * 8 + 1] >> 3 & 0x02)
592
+ | (qh[:, i * 8 + 2] >> 2 & 0x04)
593
+ | (qh[:, i * 8 + 3] >> 1 & 0x08)
594
+ | (qh[:, i * 8 + 4] << 0 & 0x10)
595
+ | (qh[:, i * 8 + 5] << 1 & 0x20)
596
+ | (qh[:, i * 8 + 6] << 2 & 0x40)
597
+ | (qh[:, i * 8 + 7] << 3 & 0x80)
598
+ )
599
+
600
+ d = d.to(torch.float16).view(torch.uint8)
601
+
602
+ return torch.cat([d, qh_packed, qs], dim=-1)
603
+
604
+
605
+ class Q5_1(__Quant, qtype=GGMLQuantizationType.Q5_1):
606
+ @classmethod
607
+ def quantize_blocks(cls, blocks: np.ndarray) -> np.ndarray:
608
+ n_blocks = blocks.shape[0]
609
+
610
+ max = blocks.max(axis=-1, keepdims=True)
611
+ min = blocks.min(axis=-1, keepdims=True)
612
+
613
+ d = (max - min) / 31
614
+ with np.errstate(divide="ignore"):
615
+ id = np.where(d == 0, 0, 1 / d)
616
+ q = (
617
+ np.trunc((blocks - min) * id + np.float32(0.5), dtype=np.float32)
618
+ .astype(np.uint8)
619
+ .clip(0, 31)
620
+ )
621
+
622
+ qs = q.reshape((n_blocks, 2, cls.block_size // 2))
623
+ qs = (qs[..., 0, :] & np.uint8(0x0F)) | (qs[..., 1, :] << np.uint8(4))
624
+
625
+ qh = np.packbits(
626
+ q.reshape((n_blocks, 1, 32)) >> np.uint8(4), axis=-1, bitorder="little"
627
+ ).reshape(n_blocks, 4)
628
+
629
+ d = d.astype(np.float16).view(np.uint8)
630
+ m = min.astype(np.float16).view(np.uint8)
631
+
632
+ return np.concatenate([d, m, qh, qs], axis=-1)
633
+
634
+ @classmethod
635
+ def dequantize_blocks(cls, blocks: np.ndarray) -> np.ndarray:
636
+ n_blocks = blocks.shape[0]
637
+
638
+ d, rest = np.hsplit(blocks, [2])
639
+ m, rest = np.hsplit(rest, [2])
640
+ qh, qs = np.hsplit(rest, [4])
641
+
642
+ d = d.view(np.float16).astype(np.float32)
643
+ m = m.view(np.float16).astype(np.float32)
644
+ qh = qh.view(np.uint32)
645
+
646
+ qh = qh.reshape((n_blocks, 1)) >> np.array(
647
+ [i for i in range(32)], dtype=np.uint32
648
+ ).reshape((1, 32))
649
+ ql = qs.reshape((n_blocks, -1, 1, cls.block_size // 2)) >> np.array(
650
+ [0, 4], dtype=np.uint8
651
+ ).reshape((1, 1, 2, 1))
652
+ qh = (qh & np.uint32(0x01)).astype(np.uint8)
653
+ ql = (ql & np.uint8(0x0F)).reshape((n_blocks, -1))
654
+
655
+ qs = (ql | (qh << np.uint8(4))).astype(np.float32)
656
+
657
+ return (d * qs) + m
658
+
659
+ @classmethod
660
+ def dequantize_blocks_pytorch(
661
+ cls, blocks, block_size, type_size, parameter
662
+ ) -> torch.Tensor:
663
+ def to_uint32(x):
664
+ # pytorch uint32 by City96 - Apache-2.0
665
+ x = x.view(torch.uint8).to(torch.int32)
666
+ return (x[:, 0] | x[:, 1] << 8 | x[:, 2] << 16 | x[:, 3] << 24).unsqueeze(1)
667
+
668
+ n_blocks = blocks.shape[0]
669
+
670
+ d, m, qh, qs = quick_split(blocks, [2, 2, 4])
671
+ d = d.view(torch.float16).to(parameter.computation_dtype)
672
+ m = m.view(torch.float16).to(parameter.computation_dtype)
673
+ qh = to_uint32(qh)
674
+
675
+ qh = qh.reshape((n_blocks, 1)) >> torch.arange(
676
+ 32, device=d.device, dtype=torch.int32
677
+ ).reshape(1, 32)
678
+ ql = qs.reshape((n_blocks, -1, 1, block_size // 2)) >> torch.tensor(
679
+ [0, 4], device=d.device, dtype=torch.uint8
680
+ ).reshape(1, 1, 2, 1)
681
+ qh = (qh & 1).to(torch.uint8)
682
+ ql = (ql & 0x0F).reshape((n_blocks, -1))
683
+
684
+ qs = ql | (qh << 4)
685
+ return (d * qs) + m
686
+
687
+
688
+ class Q8_0(__Quant, qtype=GGMLQuantizationType.Q8_0):
689
+ @classmethod
690
+ # Implementation of Q8_0 with bit-exact same results as reference implementation in ggml-quants.c
691
+ def quantize_blocks(cls, blocks: np.ndarray) -> np.ndarray:
692
+
693
+ d = abs(blocks).max(axis=1, keepdims=True) / 127
694
+ with np.errstate(divide="ignore"):
695
+ id = np.where(d == 0, 0, 1 / d)
696
+ qs = np_roundf(blocks * id)
697
+
698
+ # (n_blocks, 2)
699
+ d = d.astype(np.float16).view(np.uint8)
700
+ # (n_blocks, block_size)
701
+ qs = qs.astype(np.int8).view(np.uint8)
702
+
703
+ return np.concatenate([d, qs], axis=1)
704
+
705
+ @classmethod
706
+ def dequantize_blocks(cls, blocks: np.ndarray) -> np.ndarray:
707
+ d, x = np.split(blocks, [2], axis=1)
708
+ d = d.view(np.float16).astype(np.float32)
709
+ x = x.view(np.int8).astype(np.float32)
710
+
711
+ return x * d
712
+
713
+ @classmethod
714
+ def bake_inner(cls, parameter):
715
+ blocks = parameter.data
716
+ d, x = quick_split(blocks, [2])
717
+ x = x.view(torch.int8)
718
+ d = d.view(torch.float16).to(parameter.computation_dtype).view(torch.int8)
719
+ parameter.data = torch.cat([d, x], dim=-1).contiguous()
720
+ return
721
+
722
+ @classmethod
723
+ def dequantize_blocks_pytorch(
724
+ cls, blocks, block_size, type_size, parameter
725
+ ) -> torch.Tensor:
726
+ d, x = quick_split(blocks, [2])
727
+ d = d.view(parameter.computation_dtype)
728
+ return x * d
729
+
730
+ @classmethod
731
+ def quantize_blocks_pytorch(
732
+ cls, blocks, block_size, type_size, parent
733
+ ) -> torch.Tensor:
734
+ # Copyright Forge 2024, AGPL V3 + CC-BY SA
735
+ d = torch.abs(blocks).max(dim=1, keepdim=True).values / 127
736
+ ids = torch.where(d == 0, torch.zeros_like(d), 1 / d)
737
+ qs = torch.round(blocks * ids)
738
+ d = d.to(parent.computation_dtype).view(torch.int8)
739
+ qs = qs.to(torch.int8)
740
+ return torch.cat([d, qs], dim=1)
741
+
742
+
743
+ class Q2_K(__Quant, qtype=GGMLQuantizationType.Q2_K):
744
+ @classmethod
745
+ def dequantize_blocks(cls, blocks: np.ndarray) -> np.ndarray:
746
+ n_blocks = blocks.shape[0]
747
+
748
+ scales, rest = np.hsplit(blocks, [QK_K // 16])
749
+ qs, rest = np.hsplit(rest, [QK_K // 4])
750
+ d, dmin = np.hsplit(rest, [2])
751
+
752
+ d = d.view(np.float16).astype(np.float32)
753
+ dmin = dmin.view(np.float16).astype(np.float32)
754
+
755
+ # (n_blocks, 16, 1)
756
+ dl = (d * (scales & 0xF).astype(np.float32)).reshape((n_blocks, QK_K // 16, 1))
757
+ ml = (dmin * (scales >> 4).astype(np.float32)).reshape(
758
+ (n_blocks, QK_K // 16, 1)
759
+ )
760
+
761
+ shift = np.array([0, 2, 4, 6], dtype=np.uint8).reshape((1, 1, 4, 1))
762
+
763
+ qs = (qs.reshape((n_blocks, -1, 1, 32)) >> shift) & np.uint8(3)
764
+
765
+ qs = qs.reshape((n_blocks, QK_K // 16, 16)).astype(np.float32)
766
+
767
+ qs = dl * qs - ml
768
+
769
+ return qs.reshape((n_blocks, -1))
770
+
771
+ @classmethod
772
+ def dequantize_blocks_pytorch(
773
+ cls, blocks, block_size, type_size, parameter
774
+ ) -> torch.Tensor:
775
+ # (c) City96 || Apache-2.0 (apache.org/licenses/LICENSE-2.0)
776
+ n_blocks = blocks.shape[0]
777
+ scales, qs, d, dmin = quick_split(blocks, [QK_K // 16, QK_K // 4, 2])
778
+ d = d.view(torch.float16).to(parameter.computation_dtype)
779
+ dmin = dmin.view(torch.float16).to(parameter.computation_dtype)
780
+ # (n_blocks, 16, 1)
781
+ dl = (d * (scales & 0xF)).reshape((n_blocks, QK_K // 16, 1))
782
+ ml = (dmin * (scales >> 4)).reshape((n_blocks, QK_K // 16, 1))
783
+ shift = torch.tensor([0, 2, 4, 6], device=d.device, dtype=torch.uint8).reshape(
784
+ (1, 1, 4, 1)
785
+ )
786
+ qs = (qs.reshape((n_blocks, -1, 1, 32)) >> shift) & 3
787
+ qs = qs.reshape((n_blocks, QK_K // 16, 16))
788
+ qs = dl * qs - ml
789
+ return qs.reshape((n_blocks, -1))
790
+
791
+
792
+ class Q3_K(__Quant, qtype=GGMLQuantizationType.Q3_K):
793
+ @classmethod
794
+ def dequantize_blocks(cls, blocks: np.ndarray) -> np.ndarray:
795
+ n_blocks = blocks.shape[0]
796
+
797
+ hmask, rest = np.hsplit(blocks, [QK_K // 8])
798
+ qs, rest = np.hsplit(rest, [QK_K // 4])
799
+ scales, d = np.hsplit(rest, [12])
800
+
801
+ d = d.view(np.float16).astype(np.float32)
802
+
803
+ # The scales are packed at 6-bit each in this pattern:
804
+ # 0: IIIIAAAA
805
+ # 1: JJJJBBBB
806
+ # 2: KKKKCCCC
807
+ # 3: LLLLDDDD
808
+ # 4: MMMMEEEE
809
+ # 5: NNNNFFFF
810
+ # 6: OOOOGGGG
811
+ # 7: PPPPHHHH
812
+ # 8: MMIIEEAA
813
+ # 9: NNJJFFBB
814
+ # 10: OOKKGGCC
815
+ # 11: PPLLHHDD
816
+ lscales, hscales = np.hsplit(scales, [8])
817
+ lscales = lscales.reshape((n_blocks, 1, 8)) >> np.array(
818
+ [0, 4], dtype=np.uint8
819
+ ).reshape((1, 2, 1))
820
+ lscales = lscales.reshape((n_blocks, 16))
821
+ hscales = hscales.reshape((n_blocks, 1, 4)) >> np.array(
822
+ [0, 2, 4, 6], dtype=np.uint8
823
+ ).reshape((1, 4, 1))
824
+ hscales = hscales.reshape((n_blocks, 16))
825
+ scales = (lscales & np.uint8(0x0F)) | (
826
+ (hscales & np.uint8(0x03)) << np.uint8(4)
827
+ )
828
+ scales = (scales.astype(np.int8) - np.int8(32)).astype(np.float32)
829
+
830
+ dl = (d * scales).reshape((n_blocks, 16, 1))
831
+
832
+ ql = qs.reshape((n_blocks, -1, 1, 32)) >> np.array(
833
+ [0, 2, 4, 6], dtype=np.uint8
834
+ ).reshape((1, 1, 4, 1))
835
+ qh = hmask.reshape(n_blocks, -1, 1, 32) >> np.array(
836
+ [i for i in range(8)], dtype=np.uint8
837
+ ).reshape((1, 1, 8, 1))
838
+ ql = ql.reshape((n_blocks, 16, QK_K // 16)) & np.uint8(3)
839
+ qh = qh.reshape((n_blocks, 16, QK_K // 16)) & np.uint8(1)
840
+ qh = qh ^ np.uint8(1) # strangely, the offset is zero when the bitmask is 1
841
+ q = (ql.astype(np.int8) - (qh << np.uint8(2)).astype(np.int8)).astype(
842
+ np.float32
843
+ )
844
+
845
+ return (dl * q).reshape((n_blocks, QK_K))
846
+
847
+ @classmethod
848
+ def dequantize_blocks_pytorch(
849
+ cls, blocks, block_size, type_size, parameter
850
+ ) -> torch.Tensor:
851
+ # (c) City96 || Apache-2.0 (apache.org/licenses/LICENSE-2.0)
852
+ n_blocks = blocks.shape[0]
853
+ hmask, qs, scales, d = quick_split(blocks, [QK_K // 8, QK_K // 4, 12])
854
+ d = d.view(torch.float16).to(parameter.computation_dtype)
855
+ lscales, hscales = scales[:, :8], scales[:, 8:]
856
+ lscales = lscales.reshape((n_blocks, 1, 8)) >> torch.tensor(
857
+ [0, 4], device=d.device, dtype=torch.uint8
858
+ ).reshape((1, 2, 1))
859
+ lscales = lscales.reshape((n_blocks, 16))
860
+ hscales = hscales.reshape((n_blocks, 1, 4)) >> torch.tensor(
861
+ [0, 2, 4, 6], device=d.device, dtype=torch.uint8
862
+ ).reshape((1, 4, 1))
863
+ hscales = hscales.reshape((n_blocks, 16))
864
+ scales = (lscales & 0x0F) | ((hscales & 0x03) << 4)
865
+ scales = scales.to(torch.int8) - 32
866
+ dl = (d * scales).reshape((n_blocks, 16, 1))
867
+ ql = qs.reshape((n_blocks, -1, 1, 32)) >> torch.tensor(
868
+ [0, 2, 4, 6], device=d.device, dtype=torch.uint8
869
+ ).reshape((1, 1, 4, 1))
870
+ qh = hmask.reshape(n_blocks, -1, 1, 32) >> torch.tensor(
871
+ [i for i in range(8)], device=d.device, dtype=torch.uint8
872
+ ).reshape((1, 1, 8, 1))
873
+ ql = ql.reshape((n_blocks, 16, QK_K // 16)) & 3
874
+ qh = (qh.reshape((n_blocks, 16, QK_K // 16)) & 1) ^ 1
875
+ q = ql.to(torch.int8) - (qh << 2).to(torch.int8)
876
+ return (dl * q).reshape((n_blocks, QK_K))
877
+
878
+
879
+ class Q4_K(__Quant, qtype=GGMLQuantizationType.Q4_K):
880
+ K_SCALE_SIZE = 12
881
+
882
+ @staticmethod
883
+ def get_scale_min(scales: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
884
+ n_blocks = scales.shape[0]
885
+ scales = scales.view(np.uint8)
886
+ ### Unpacking the following: ###
887
+ # 0 EEAAAAAA
888
+ # 1 FFBBBBBB
889
+ # 2 GGCCCCCC
890
+ # 3 HHDDDDDD
891
+ # 4 eeaaaaaa
892
+ # 5 ffbbbbbb
893
+ # 6 ggcccccc
894
+ # 7 hhdddddd
895
+ # 8 eeeeEEEE
896
+ # 9 ffffFFFF
897
+ # 10 ggggGGGG
898
+ # 11 hhhhHHHH
899
+ scales = scales.reshape((n_blocks, 3, 4))
900
+ d, m, m_d = np.split(scales, 3, axis=-2)
901
+
902
+ sc = np.concatenate([d & 0x3F, (m_d & 0x0F) | ((d >> 2) & 0x30)], axis=-1)
903
+ min = np.concatenate([m & 0x3F, (m_d >> 4) | ((m >> 2) & 0x30)], axis=-1)
904
+
905
+ return (sc.reshape((n_blocks, 8)), min.reshape((n_blocks, 8)))
906
+
907
+ @staticmethod
908
+ def get_scale_min_pytorch(scales):
909
+ n_blocks = scales.shape[0]
910
+ scales = scales.view(torch.uint8)
911
+ scales = scales.reshape((n_blocks, 3, 4))
912
+ d, m, m_d = torch.split(scales, scales.shape[-2] // 3, dim=-2)
913
+ sc = torch.cat([d & 0x3F, (m_d & 0x0F) | ((d >> 2) & 0x30)], dim=-1)
914
+ min = torch.cat([m & 0x3F, (m_d >> 4) | ((m >> 2) & 0x30)], dim=-1)
915
+ return (sc.reshape((n_blocks, 8)), min.reshape((n_blocks, 8)))
916
+
917
+ @classmethod
918
+ def dequantize_blocks(cls, blocks: np.ndarray) -> np.ndarray:
919
+ n_blocks = blocks.shape[0]
920
+
921
+ d, rest = np.hsplit(blocks, [2])
922
+ dmin, rest = np.hsplit(rest, [2])
923
+ scales, qs = np.hsplit(rest, [cls.K_SCALE_SIZE])
924
+
925
+ d = d.view(np.float16).astype(np.float32)
926
+ dmin = dmin.view(np.float16).astype(np.float32)
927
+
928
+ sc, m = Q4_K.get_scale_min(scales)
929
+
930
+ d = (d * sc.astype(np.float32)).reshape((n_blocks, -1, 1))
931
+ dm = (dmin * m.astype(np.float32)).reshape((n_blocks, -1, 1))
932
+
933
+ qs = qs.reshape((n_blocks, -1, 1, 32)) >> np.array(
934
+ [0, 4], dtype=np.uint8
935
+ ).reshape((1, 1, 2, 1))
936
+ qs = (qs & np.uint8(0x0F)).reshape((n_blocks, -1, 32)).astype(np.float32)
937
+
938
+ return (d * qs - dm).reshape((n_blocks, QK_K))
939
+
940
+ @classmethod
941
+ def bake_inner(cls, parameter): # Only compute one time when model load
942
+ # Copyright Forge 2024
943
+
944
+ blocks = parameter.data
945
+ n_blocks = blocks.shape[0]
946
+ d, dmin, scales, qs = quick_split(blocks, [2, 2, cls.K_SCALE_SIZE])
947
+ d = d.view(torch.float16).to(parameter.computation_dtype)
948
+ dmin = dmin.view(torch.float16).to(parameter.computation_dtype)
949
+ sc, m = Q4_K.get_scale_min_pytorch(scales)
950
+ d = (d * sc).reshape((n_blocks, -1, 1))
951
+ dm = (dmin * m).reshape((n_blocks, -1, 1)).to(parameter.computation_dtype)
952
+
953
+ qs = qs.reshape((n_blocks, -1, 1, 32))
954
+ qs = change_4bits_order(qs)
955
+
956
+ d = d.view(torch.uint8).reshape((n_blocks, -1))
957
+ dm = dm.view(torch.uint8).reshape((n_blocks, -1))
958
+ qs = qs.view(torch.uint8)
959
+
960
+ parameter.data = torch.cat([d, dm, qs], dim=-1).contiguous()
961
+ return
962
+
963
+ @classmethod
964
+ def dequantize_blocks_pytorch(
965
+ cls, blocks, block_size, type_size, parameter
966
+ ) -> torch.Tensor:
967
+ # Compute in each diffusion iteration
968
+
969
+ n_blocks = blocks.shape[0]
970
+
971
+ d, dm, qs = quick_split(blocks, [16, 16])
972
+ d = d.view(parameter.computation_dtype).view((n_blocks, -1, 1))
973
+ dm = dm.view(parameter.computation_dtype).view((n_blocks, -1, 1))
974
+ qs = quick_unpack_4bits_u(qs).view((n_blocks, -1, 32))
975
+
976
+ return (d * qs - dm).reshape((n_blocks, QK_K))
977
+
978
+
979
+ class Q5_K(__Quant, qtype=GGMLQuantizationType.Q5_K):
980
+ @classmethod
981
+ def dequantize_blocks(cls, blocks: np.ndarray) -> np.ndarray:
982
+ n_blocks = blocks.shape[0]
983
+
984
+ d, rest = np.hsplit(blocks, [2])
985
+ dmin, rest = np.hsplit(rest, [2])
986
+ scales, rest = np.hsplit(rest, [Q4_K.K_SCALE_SIZE])
987
+ qh, qs = np.hsplit(rest, [QK_K // 8])
988
+
989
+ d = d.view(np.float16).astype(np.float32)
990
+ dmin = dmin.view(np.float16).astype(np.float32)
991
+
992
+ sc, m = Q4_K.get_scale_min(scales)
993
+
994
+ d = (d * sc.astype(np.float32)).reshape((n_blocks, -1, 1))
995
+ dm = (dmin * m.astype(np.float32)).reshape((n_blocks, -1, 1))
996
+
997
+ ql = qs.reshape((n_blocks, -1, 1, 32)) >> np.array(
998
+ [0, 4], dtype=np.uint8
999
+ ).reshape((1, 1, 2, 1))
1000
+ qh = qh.reshape((n_blocks, -1, 1, 32)) >> np.array(
1001
+ [i for i in range(8)], dtype=np.uint8
1002
+ ).reshape((1, 1, 8, 1))
1003
+ ql = (ql & np.uint8(0x0F)).reshape((n_blocks, -1, 32))
1004
+ qh = (qh & np.uint8(0x01)).reshape((n_blocks, -1, 32))
1005
+ q = (ql | (qh << np.uint8(4))).astype(np.float32)
1006
+
1007
+ return (d * q - dm).reshape((n_blocks, QK_K))
1008
+
1009
+ @classmethod
1010
+ def dequantize_blocks_pytorch(
1011
+ cls, blocks, block_size, type_size, parameter
1012
+ ) -> torch.Tensor:
1013
+ # (c) City96 || Apache-2.0 (apache.org/licenses/LICENSE-2.0)
1014
+ QK_K = 256
1015
+ K_SCALE_SIZE = 12
1016
+ n_blocks = blocks.shape[0]
1017
+ d, dmin, scales, qh, qs = quick_split(blocks, [2, 2, K_SCALE_SIZE, QK_K // 8])
1018
+ d = d.view(torch.float16).to(parameter.computation_dtype)
1019
+ dmin = dmin.view(torch.float16).to(parameter.computation_dtype)
1020
+ sc, m = Q4_K.get_scale_min_pytorch(scales)
1021
+ d = (d * sc).reshape((n_blocks, -1, 1))
1022
+ dm = (dmin * m).reshape((n_blocks, -1, 1))
1023
+ ql = qs.reshape((n_blocks, -1, 1, 32)) >> torch.tensor(
1024
+ [0, 4], device=d.device, dtype=torch.uint8
1025
+ ).reshape((1, 1, 2, 1))
1026
+ qh = qh.reshape((n_blocks, -1, 1, 32)) >> torch.tensor(
1027
+ [i for i in range(8)], device=d.device, dtype=torch.uint8
1028
+ ).reshape((1, 1, 8, 1))
1029
+ ql = (ql & 0x0F).reshape((n_blocks, -1, 32))
1030
+ qh = (qh & 0x01).reshape((n_blocks, -1, 32))
1031
+ q = ql | (qh << 4)
1032
+ return (d * q - dm).reshape((n_blocks, QK_K))
1033
+
1034
+
1035
+ class Q6_K(__Quant, qtype=GGMLQuantizationType.Q6_K):
1036
+ @classmethod
1037
+ def dequantize_blocks(cls, blocks: np.ndarray) -> np.ndarray:
1038
+ n_blocks = blocks.shape[0]
1039
+
1040
+ ql, rest = np.hsplit(blocks, [QK_K // 2])
1041
+ qh, rest = np.hsplit(rest, [QK_K // 4])
1042
+ scales, d = np.hsplit(rest, [QK_K // 16])
1043
+
1044
+ scales = scales.view(np.int8).astype(np.float32)
1045
+ d = d.view(np.float16).astype(np.float32)
1046
+ d = (d * scales).reshape((n_blocks, QK_K // 16, 1))
1047
+
1048
+ ql = ql.reshape((n_blocks, -1, 1, 64)) >> np.array(
1049
+ [0, 4], dtype=np.uint8
1050
+ ).reshape((1, 1, 2, 1))
1051
+ ql = (ql & np.uint8(0x0F)).reshape((n_blocks, -1, 32))
1052
+ qh = qh.reshape((n_blocks, -1, 1, 32)) >> np.array(
1053
+ [0, 2, 4, 6], dtype=np.uint8
1054
+ ).reshape((1, 1, 4, 1))
1055
+ qh = (qh & np.uint8(0x03)).reshape((n_blocks, -1, 32))
1056
+ q = (ql | (qh << np.uint8(4))).astype(np.int8) - np.int8(32)
1057
+ q = q.reshape((n_blocks, QK_K // 16, -1)).astype(np.float32)
1058
+
1059
+ return (d * q).reshape((n_blocks, QK_K))
1060
+
1061
+ @classmethod
1062
+ def dequantize_blocks_pytorch(
1063
+ cls, blocks, block_size, type_size, parameter
1064
+ ) -> torch.Tensor:
1065
+ # Written by ChatGPT
1066
+ n_blocks = blocks.shape[0]
1067
+ (
1068
+ ql,
1069
+ qh,
1070
+ scales,
1071
+ d,
1072
+ ) = quick_split(blocks, [QK_K // 2, QK_K // 4, QK_K // 16])
1073
+ scales = scales.view(torch.int8).to(parameter.computation_dtype)
1074
+ d = d.view(torch.float16).to(parameter.computation_dtype)
1075
+ d = (d * scales).reshape((n_blocks, QK_K // 16, 1))
1076
+ ql = ql.reshape((n_blocks, -1, 1, 64)) >> torch.tensor(
1077
+ [0, 4], device=d.device, dtype=torch.uint8
1078
+ ).reshape((1, 1, 2, 1))
1079
+ ql = (ql & 0x0F).reshape((n_blocks, -1, 32))
1080
+ qh = qh.reshape((n_blocks, -1, 1, 32)) >> torch.tensor(
1081
+ [0, 2, 4, 6], device=d.device, dtype=torch.uint8
1082
+ ).reshape((1, 1, 4, 1))
1083
+ qh = (qh & 0x03).reshape((n_blocks, -1, 32))
1084
+ q = (ql | (qh << 4)).to(torch.int8) - 32
1085
+ q = q.reshape((n_blocks, QK_K // 16, -1))
1086
+ return (d * q).reshape((n_blocks, QK_K))
1087
+
1088
+
1089
+ class IQ2_XXS(__Quant, qtype=GGMLQuantizationType.IQ2_XXS):
1090
+ ksigns: bytes = (
1091
+ b"\x00\x81\x82\x03\x84\x05\x06\x87\x88\x09\x0a\x8b\x0c\x8d\x8e\x0f"
1092
+ b"\x90\x11\x12\x93\x14\x95\x96\x17\x18\x99\x9a\x1b\x9c\x1d\x1e\x9f"
1093
+ b"\xa0\x21\x22\xa3\x24\xa5\xa6\x27\x28\xa9\xaa\x2b\xac\x2d\x2e\xaf"
1094
+ b"\x30\xb1\xb2\x33\xb4\x35\x36\xb7\xb8\x39\x3a\xbb\x3c\xbd\xbe\x3f"
1095
+ b"\xc0\x41\x42\xc3\x44\xc5\xc6\x47\x48\xc9\xca\x4b\xcc\x4d\x4e\xcf"
1096
+ b"\x50\xd1\xd2\x53\xd4\x55\x56\xd7\xd8\x59\x5a\xdb\x5c\xdd\xde\x5f"
1097
+ b"\x60\xe1\xe2\x63\xe4\x65\x66\xe7\xe8\x69\x6a\xeb\x6c\xed\xee\x6f"
1098
+ b"\xf0\x71\x72\xf3\x74\xf5\xf6\x77\x78\xf9\xfa\x7b\xfc\x7d\x7e\xff"
1099
+ )
1100
+
1101
+ # iq2xxs_grid, but with each byte of the original packed in 2 bits,
1102
+ # by mapping 0x08 to 0, 0x19 to 1, and 0x2b to 2.
1103
+ grid_shape = (256, 8)
1104
+ grid_map = (0x08, 0x19, 0x2B)
1105
+ grid_hex = (
1106
+ b"00000200050008000a00110014002000220028002a0041004400500058006100"
1107
+ b"6400800082008a00a20001010401100115014001840198010002020222028202"
1108
+ b"010404041004210424044004420448046004810484049004a404000502050805"
1109
+ b"200546056905800591050906100640068406a406000805080808140828084108"
1110
+ b"440850085208880804094009020a140a01100410101021104010601084109010"
1111
+ b"951000110811201150115a118011241245120014081420142514491480141815"
1112
+ b"6215001616160118041810184018811800190519a019511a002002200a204420"
1113
+ b"6120802082202921482100220222012404241024402456240025412564259026"
1114
+ b"082820289428442a014004401040184021402440404048405640604081408440"
1115
+ b"9040004120416141804185410142104248425642684200440844204480449944"
1116
+ b"124524450046014804481048404845480049584961498249454a904a00500850"
1117
+ b"1150195020508050885004514251a4519152905492540a550156545600581158"
1118
+ b"195864584059085a046010604060686000615561186260620064056410651265"
1119
+ b"84654268008002800a8041808280048118814081118201840484108415844084"
1120
+ b"608400854685948509864086608602880489118a0490109024904090a1901691"
1121
+ b"8091459200942294449451958198209902a050a085a009a100a218a450a804a9"
1122
+ )
1123
+
1124
+ @classmethod
1125
+ def dequantize_blocks(cls, blocks: np.ndarray) -> np.ndarray:
1126
+ n_blocks = blocks.shape[0]
1127
+
1128
+ d, qs = np.hsplit(blocks, [2])
1129
+
1130
+ d = d.view(np.float16).astype(np.float32)
1131
+
1132
+ qs = qs.view(np.uint32).reshape(n_blocks, -1, 2)
1133
+
1134
+ db = (
1135
+ d
1136
+ * (np.float32(0.5) + (qs[..., 1] >> 28).astype(np.float32))
1137
+ * np.float32(0.25)
1138
+ )
1139
+ db = db.reshape((n_blocks, -1, 1, 1))
1140
+
1141
+ # get the sign indices and unpack the bits
1142
+ signs = qs[..., 1].reshape((n_blocks, -1, 1)) >> np.array(
1143
+ [0, 7, 14, 21], dtype=np.uint32
1144
+ ).reshape((1, 1, 4))
1145
+ ksigns = np.frombuffer(cls.ksigns, dtype=np.uint8).reshape((1, 1, 1, 128))
1146
+ signs = (signs & np.uint32(0x7F)).reshape((n_blocks, -1, 4, 1))
1147
+ signs = np.take_along_axis(ksigns, signs, axis=-1)
1148
+ signs = signs.reshape((n_blocks, -1, 4, 1)) >> np.array(
1149
+ [i for i in range(8)], dtype=np.uint8
1150
+ ).reshape((1, 1, 1, 8))
1151
+ signs = signs & np.uint8(0x01)
1152
+ signs = np.where(signs == 0, np.float32(1), np.float32(-1))
1153
+ signs = signs.reshape((n_blocks, -1, 4, 8))
1154
+
1155
+ assert cls.grid is not None
1156
+ grid = np.take_along_axis(
1157
+ cls.grid,
1158
+ qs[..., 0].copy().view(np.uint8).reshape((n_blocks, -1, 1, 1)),
1159
+ axis=-2,
1160
+ )
1161
+ grid = grid.reshape((n_blocks, -1, 4, 8))
1162
+
1163
+ return (db * grid * signs).reshape((n_blocks, -1))
1164
+
1165
+
1166
+ class IQ2_XS(__Quant, qtype=GGMLQuantizationType.IQ2_XS):
1167
+ # iq2xs_grid, but with each byte of the original packed in 2 bits,
1168
+ # by mapping 0x08 to 0, 0x19 to 1, and 0x2b to 2.
1169
+ grid_shape = (512, 8)
1170
+ grid_map = (0x08, 0x19, 0x2B)
1171
+ grid_hex = (
1172
+ b"00000200050008000a0011001400160019002000220025002800410044004600"
1173
+ b"49005000520055005800610064008000820085008800910094009900a0000101"
1174
+ b"04010601090110011201150118011a0121012401400142014501480151015401"
1175
+ b"6001680181018401900100020202050208021102140220024102440250025502"
1176
+ b"80028a0201040404060409041004120415041804210424044004420445044804"
1177
+ b"5104540456046004810484049004000502050505080511051405200541054405"
1178
+ b"500561058005010604061006260640064206840600080208050808080a081108"
1179
+ b"14082008250841084408500858088008a008aa08010904091009400981098909"
1180
+ b"000a200a280a960aa00a01100410061009101010121015101810211024104010"
1181
+ b"4210451048105110541060106a10811084109010001102110511081111111411"
1182
+ b"2011411144115011801194119611011204120612101240126012001402140514"
1183
+ b"0814111414142014411444144914501464148014011504151015401500161416"
1184
+ b"49160118041810181218401854188618001905196619511aa91a002002200520"
1185
+ b"08200a201120142020204120442050208020a020012104211021402148216521"
1186
+ b"002222228022a82201240424102429244024002541255225992501261a26a626"
1187
+ b"002808280a28202855288828a22868299029082a202a822a882a8a2a01400440"
1188
+ b"0640094010401240154018402140244040404240454048404a40514054406040"
1189
+ b"6540814084409040004102410541084111411441204141414441504180418541"
1190
+ b"a241014204421042124229424042004402440544084411441444194420444144"
1191
+ b"4444504480449444014504451045244540459a4500460a464446504601480448"
1192
+ b"1048404845485448624800491149444950496949044a00500250055008501150"
1193
+ b"145020502850415044505050805001510451105115514051425100524452aa52"
1194
+ b"0154045410542154405460548154a154005508558055885521566856a1560058"
1195
+ b"14584158505899581a5940594259855a0160046010604060546062608660a960"
1196
+ b"006124624a62926200641664106540654565a46501686a682569066a546a626a"
1197
+ b"00800280058008801180148020802a8041804480508080808280a880aa800181"
1198
+ b"0481068110814081518159810082208280828282a082a8820184048410841284"
1199
+ b"158440846084898400854485a58518866a860088088825885a8880888288a888"
1200
+ b"0689228a808a888a968aa88a0190049010904090569084900091229164915692"
1201
+ b"89920094059444945094589429959095929541965198a6984999159a609a00a0"
1202
+ b"02a008a00aa020a02aa0a0a051a159a1a6a100a202a208a22aa280a2a0a240a4"
1203
+ b"95a465a698a60aa820a822a828a8a0a8a8a804a984a986a928aa2aaa91aaaaaa"
1204
+ )
1205
+
1206
+ @classmethod
1207
+ def dequantize_blocks(cls, blocks: np.ndarray) -> np.ndarray:
1208
+ n_blocks = blocks.shape[0]
1209
+
1210
+ d, rest = np.hsplit(blocks, [2])
1211
+ qs, scales = np.hsplit(rest, [2 * QK_K // 8])
1212
+
1213
+ d = d.view(np.float16).astype(np.float32)
1214
+ qs = qs.view(np.uint16)
1215
+
1216
+ scales = scales.reshape((n_blocks, -1, 1)) >> np.array(
1217
+ [0, 4], dtype=np.uint8
1218
+ ).reshape((1, 1, 2))
1219
+ scales = (scales & 0x0F).reshape((n_blocks, -1))
1220
+ db = d * (np.float32(0.5) + scales) * np.float32(0.25)
1221
+ db = db.reshape((n_blocks, -1, 1, 1))
1222
+
1223
+ # get the sign indices and unpack the bits
1224
+ signs = np.frombuffer(IQ2_XXS.ksigns, dtype=np.uint8).reshape(1, 1, 128)
1225
+ signs = np.take_along_axis(signs, (qs >> 9).reshape((n_blocks, -1, 1)), axis=-1)
1226
+ signs = signs.reshape((n_blocks, -1, 1)) >> np.array(
1227
+ [i for i in range(8)], dtype=np.uint8
1228
+ ).reshape((1, 1, 8))
1229
+ signs = signs & np.uint8(0x01)
1230
+ signs = np.where(signs == 0, np.float32(1), np.float32(-1))
1231
+ signs = signs.reshape((n_blocks, -1, 2, 8))
1232
+
1233
+ assert cls.grid is not None
1234
+ grid = np.take_along_axis(
1235
+ cls.grid, (qs & np.uint16(511)).reshape((n_blocks, -1, 1, 1)), axis=-2
1236
+ )
1237
+ grid = grid.reshape((n_blocks, -1, 2, 8))
1238
+
1239
+ return (db * grid * signs).reshape((n_blocks, -1))
1240
+
1241
+
1242
+ class IQ2_S(__Quant, qtype=GGMLQuantizationType.IQ2_S):
1243
+ # iq2s_grid, but with each byte of the original packed in 2 bits,
1244
+ # by mapping 0x08 to 0, 0x19 to 1, and 0x2b to 2.
1245
+ grid_shape = (1024, 8)
1246
+ grid_map = (0x08, 0x19, 0x2B)
1247
+ grid_hex = (
1248
+ b"00000200050008000a0011001400160019002000220025002800410044004600"
1249
+ b"490050005200550058006100640066006900800082008500880091009400a000"
1250
+ b"a500aa0001010401060109011001120115011801210124014001420145014801"
1251
+ b"510154015601590160016501680181018401900192019501a101a40100020202"
1252
+ b"050208021102140220022a02410244024602490250025502800285028a029402"
1253
+ b"a202010404040604090410041204150418042104240426042904400442044504"
1254
+ b"48044a0451045404560459046004620465048104840486048904900495049804"
1255
+ b"a104a40400050205050508050a05110514051605190520052505280541054405"
1256
+ b"46054905500552055505580561056405800582058505880591059405a0050106"
1257
+ b"0406060609061006150640064506480651065406600681068406900600080208"
1258
+ b"050808081108140816081908200825082a084108440846084908500852085508"
1259
+ b"580861086408800885089408aa08010904091009120915091809210940094509"
1260
+ b"480951095409600981099009000a110a140a220a280a2a0a500a990a01100410"
1261
+ b"0610091010101210151018102110241026104010421045104810511054105610"
1262
+ b"59106010621065106810811084108610901095109810a110a410001102110511"
1263
+ b"08110a1111111411161119112011221125112811411144114611491150115211"
1264
+ b"5511581161116411801182118511881191119411011204120912101215122112"
1265
+ b"2412401245125112541281128412901200140214051408141114141416141914"
1266
+ b"2014251428144114441446144914501452145514581461146414801482148514"
1267
+ b"881491149414a014011504150615091510151215151518152115241540154215"
1268
+ b"4515481551155415601581158415901500160516081611161416201641164416"
1269
+ b"50168016aa160118041806180918101815181818211840184218451848185118"
1270
+ b"541860188118841800190219051908191119141920194119441950196919a219"
1271
+ b"041a101a401a561a00200220052008201120142016201920202025202a204120"
1272
+ b"4420502052205520642080208a209420aa200121042110211221152121214021"
1273
+ b"4221452151215421602181218421902100220a22222228222a22442250228822"
1274
+ b"8a22a82201240424062409241024152418242124242440244224452448245124"
1275
+ b"5424602481248424902400250525082511251425202541254425502566258025"
1276
+ b"0126042610264026592600280528112814284128442850288a28aa2801290429"
1277
+ b"102995290a2a222a642a882a8a2a014004400640094010401240154018401a40"
1278
+ b"21402440264040404240454048404a4051405440564059406040624065408140"
1279
+ b"8440904095409840a140a4400041024105410841114114411641194120412241"
1280
+ b"2541414144414641494150415241554158416141644180418241854188419141"
1281
+ b"9441a04101420442104212421542184224424042454248425142544260428142"
1282
+ b"844200440244054408440a441144144416441944204422442544284441444444"
1283
+ b"46444944504452445544584461446444804482448544884491449444a0440145"
1284
+ b"0445064509451045124515451845214524454045424545454845514554456045"
1285
+ b"6a4581458445904500460246054608461146144620464146444650468046a546"
1286
+ b"0148044809481048124815481848214824484048424845484848514854486048"
1287
+ b"84489048004902490549084911491449204941494449504980499649014a044a"
1288
+ b"104a404a00500250055008501150145016501950205022502550285041504450"
1289
+ b"4650495050505250555058506150645080508250855088509150945001510451"
1290
+ b"0651095110511251155118512151245140514251455148515151545160518151"
1291
+ b"8451905100520552085211521452205241524452505269528052015404540654"
1292
+ b"0954105412541554185421542454405442544554485451545454605481548454"
1293
+ b"9054005502550555085511551455205541554455505580550156045610562656"
1294
+ b"405600580258055808581158145820584158445850585a588058015904591059"
1295
+ b"4059005a195a855aa85a01600460066010601260156018602160246040604560"
1296
+ b"4860516054606060846090600061026105610861116114612061416144615061"
1297
+ b"806199610462106240625662a162006405640864116414642064416444645064"
1298
+ b"806401650465106540654a656865926500669466016804681068656898680069"
1299
+ b"2a69426aa16a0080028005800880118014801980208025804180448050805280"
1300
+ b"5580588061808080858091809480018104810981108112811581188121812481"
1301
+ b"408142814581488151815481818184819081a981008205820a82118214824182"
1302
+ b"4482508201840484068409841084128415841884218440844284458448845184"
1303
+ b"5484608481848484908400850285058508851185148520854185448550858085"
1304
+ b"8a85018604861086298640860088058811881488418844885088a28801890489"
1305
+ b"40896589228a588a5a8a828aa28a019004900990109012901590189024904090"
1306
+ b"4290459048905190549060908190849090900091059111911491419144915091"
1307
+ b"5a910192049210924092a6920094029405940894119414942094419444945094"
1308
+ b"8094969401950495109540959895a19500964696649601980498109826984098"
1309
+ b"a998009949995299909a00a005a00aa014a022a02aa041a044a050a0a2a0aaa0"
1310
+ b"40a165a102a20aa222a228a22aa282a288a28aa2a8a201a404a410a440a489a4"
1311
+ b"a4a400a519a551a60aa828a8a2a854a986a908aa0aaa20aa22aa28aa88aaaaaa"
1312
+ )
1313
+
1314
+ @classmethod
1315
+ def dequantize_blocks(cls, blocks: np.ndarray) -> np.ndarray:
1316
+ n_blocks = blocks.shape[0]
1317
+
1318
+ d, rest = np.hsplit(blocks, [2])
1319
+ qs, rest = np.hsplit(rest, [QK_K // 8])
1320
+ signs, rest = np.hsplit(rest, [QK_K // 8])
1321
+ qh, scales = np.hsplit(rest, [QK_K // 32])
1322
+
1323
+ d = d.view(np.float16).astype(np.float32)
1324
+
1325
+ scales = scales.reshape((n_blocks, -1, 1)) >> np.array(
1326
+ [0, 4], dtype=np.uint8
1327
+ ).reshape((1, 1, 2))
1328
+ scales = (scales & 0x0F).reshape((n_blocks, -1))
1329
+ db = d * (np.float32(0.5) + scales) * np.float32(0.25)
1330
+ db = db.reshape((n_blocks, -1, 1, 1))
1331
+
1332
+ # unpack the sign bits
1333
+ signs = signs.reshape((n_blocks, -1, 1)) >> np.array(
1334
+ [i for i in range(8)], dtype=np.uint8
1335
+ ).reshape((1, 1, 8))
1336
+ signs = signs & np.uint8(0x01)
1337
+ signs = np.where(signs == 0, np.float32(1), np.float32(-1))
1338
+ signs = signs.reshape((n_blocks, -1, 2, 8))
1339
+
1340
+ qh = qh.reshape((n_blocks, -1, 1)) >> np.array(
1341
+ [0, 2, 4, 6], dtype=np.uint8
1342
+ ).reshape((1, 1, 4))
1343
+ qs = qs.astype(np.uint16) | ((qh & 0x03).astype(np.uint16) << 8).reshape(
1344
+ (n_blocks, -1)
1345
+ )
1346
+
1347
+ assert cls.grid is not None
1348
+ grid = np.take_along_axis(cls.grid, qs.reshape((n_blocks, -1, 1, 1)), axis=-2)
1349
+ grid = grid.reshape((n_blocks, -1, 2, 8))
1350
+
1351
+ return (db * grid * signs).reshape((n_blocks, -1))
1352
+
1353
+
1354
+ class IQ3_XXS(__Quant, qtype=GGMLQuantizationType.IQ3_XXS):
1355
+ grid_shape = (256, 4)
1356
+ grid_map = (0x04, 0x0C, 0x14, 0x1C, 0x24, 0x2C, 0x34, 0x3E)
1357
+ grid_hex = (
1358
+ b"0000020004001100130017002000220031004200730075000101030110011201"
1359
+ b"2101250130013201410154017001000202020402110220022202310233023702"
1360
+ b"5102570275020103070310031203250370031304370444045704730475040105"
1361
+ b"0705320552053506640610071407160743076107011003101010121021102310"
1362
+ b"3010321034104710501000110211111120112211011203121012121221123012"
1363
+ b"7212001302132013311346136613011405145014201524154615711505162217"
1364
+ b"4017002002201120132020202220262031204220012103210521102112212121"
1365
+ b"3021632167217021002202221122172220222222372240225522012310231423"
1366
+ b"7023742335245324032527254125742501270327162745270130103012302130"
1367
+ b"2330503065307230003102312031313144314631013203321032253252327232"
1368
+ b"1133333330344734723400350635223555351436363663363337603704401740"
1369
+ b"3540374053405740744120423742404260426642074345430444514464442545"
1370
+ b"4345704505471047124730471250415070500051065126515551145232527252"
1371
+ b"0253535310542354275472540255315550562457425724604460466064602161"
1372
+ b"6161176264623063366344640565526533660367216703700570077010703270"
1373
+ b"5270267140711272457252720073157333736073217441740075027524753076"
1374
+ )
1375
+
1376
+ @classmethod
1377
+ def dequantize_blocks(cls, blocks: np.ndarray) -> np.ndarray:
1378
+ n_blocks = blocks.shape[0]
1379
+
1380
+ d, rest = np.hsplit(blocks, [2])
1381
+ qs, scales = np.hsplit(rest, [QK_K // 4])
1382
+
1383
+ d = d.view(np.float16).astype(np.float32)
1384
+ scales = scales.view(np.uint32)
1385
+
1386
+ db = d * (np.float32(0.5) + (scales >> 28).astype(np.float32)) * np.float32(0.5)
1387
+ db = db.reshape((n_blocks, -1, 1, 1))
1388
+
1389
+ # get the sign indices and unpack the bits
1390
+ signs = scales.reshape((n_blocks, -1, 1)) >> np.array(
1391
+ [0, 7, 14, 21], dtype=np.uint32
1392
+ ).reshape((1, 1, 4))
1393
+ ksigns = np.frombuffer(IQ2_XXS.ksigns, dtype=np.uint8).reshape((1, 1, 1, 128))
1394
+ signs = (signs & np.uint32(0x7F)).reshape((n_blocks, -1, 4, 1))
1395
+ signs = np.take_along_axis(ksigns, signs, axis=-1)
1396
+ signs = signs.reshape((n_blocks, -1, 4, 1)) >> np.array(
1397
+ [i for i in range(8)], dtype=np.uint8
1398
+ ).reshape((1, 1, 1, 8))
1399
+ signs = signs & np.uint8(0x01)
1400
+ signs = np.where(signs == 0, np.float32(1), np.float32(-1))
1401
+ signs = signs.reshape((n_blocks, -1, 4, 8))
1402
+
1403
+ assert cls.grid is not None
1404
+ grid = np.take_along_axis(cls.grid, qs.reshape((n_blocks, -1, 1, 1)), axis=-2)
1405
+ grid = grid.reshape((n_blocks, -1, 4, 8))
1406
+
1407
+ return (db * grid * signs).reshape((n_blocks, -1))
1408
+
1409
+
1410
+ class IQ3_S(__Quant, qtype=GGMLQuantizationType.IQ3_S):
1411
+ grid_shape = (512, 4)
1412
+ grid_map = (0x01, 0x03, 0x05, 0x07, 0x09, 0x0B, 0x0D, 0x0F)
1413
+ grid_hex = (
1414
+ b"0000010002000500070010001100120014001600200021002500330040004200"
1415
+ b"4500470051005300600062007100740077000001010102010401100111011501"
1416
+ b"2001230127013101350144016101650172010002010205020702100213021602"
1417
+ b"2102250230023402420245024702510253027002730203031103150320032203"
1418
+ b"3103330336034403500352036703710375030004130417042104240432044004"
1419
+ b"4304510470040205040520052205260533054105450547056605730506061106"
1420
+ b"1306310652067106000702070407200722072607330750075407001001100210"
1421
+ b"0410101011101310151017102010221031103410361054105610611072100011"
1422
+ b"0111031106111011141121113011331141115011521170117611001212121512"
1423
+ b"1712201224123212401243125512601272120113041307131013131321132713"
1424
+ b"3013341341136213701303140514121414143114331442144614501454140115"
1425
+ b"1015131521153015321551152016241627164416461601170317101712172117"
1426
+ b"3517411762177017002001200320052007201020122014201620212023202720"
1427
+ b"3020322041204320452050205220672070207320752000210221102113211721"
1428
+ b"2221252131213421422151210122042207222122232230223722412253225722"
1429
+ b"7122742200230223052311232223242331233323422350236623012407242024"
1430
+ b"2324322435244124722475240425112522253725402553257025002602260726"
1431
+ b"2126552661260527112726273027432750270230113013301530173022303130"
1432
+ b"3330353042304430473051306330713001310331053114312131233140316031"
1433
+ b"7231763100321232203232323432503201331033143321332333273330334133"
1434
+ b"4333473355337333033411341634223431345234603464340135103512352535"
1435
+ b"3235443556357335163641360137033720372237353700400440124020402440"
1436
+ b"2740324041405040704002410741114113412241304135414341514155410142"
1437
+ b"0342104215422142334240425742624270420443114313432043224331433543"
1438
+ b"0044024424443744404471440545074521456245134634466046104715473047"
1439
+ b"4347514702501050145022504050445047505250665074500151035105511251"
1440
+ b"2151325172510052115223523052365253520253075310532753445351536553"
1441
+ b"7353015404542054325446541255265551555355425602570457225711601360"
1442
+ b"1560316033606060006120612761646112623462426255626262706200631463"
1443
+ b"2163406325644364626400650365346560650566406611671367007004700770"
1444
+ b"2070227036704070547062700271117124714371457101720472107216722172"
1445
+ b"3072517202733273357353730174057413742074507422754275027631760077"
1446
+ )
1447
+
1448
+ @classmethod
1449
+ def dequantize_blocks(cls, blocks: np.ndarray) -> np.ndarray:
1450
+ n_blocks = blocks.shape[0]
1451
+
1452
+ d, rest = np.hsplit(blocks, [2])
1453
+ qs, rest = np.hsplit(rest, [QK_K // 4])
1454
+ qh, rest = np.hsplit(rest, [QK_K // 32])
1455
+ signs, scales = np.hsplit(rest, [QK_K // 8])
1456
+
1457
+ d = d.view(np.float16).astype(np.float32)
1458
+
1459
+ scales = scales.reshape((n_blocks, -1, 1)) >> np.array(
1460
+ [0, 4], dtype=np.uint8
1461
+ ).reshape((1, 1, 2))
1462
+ scales = (scales & 0x0F).reshape((n_blocks, -1))
1463
+ db = d * (1 + 2 * scales)
1464
+ db = db.reshape((n_blocks, -1, 1, 1))
1465
+
1466
+ # unpack the sign bits
1467
+ signs = signs.reshape((n_blocks, -1, 1)) >> np.array(
1468
+ [i for i in range(8)], dtype=np.uint8
1469
+ ).reshape((1, 1, 8))
1470
+ signs = signs & np.uint8(0x01)
1471
+ signs = np.where(signs == 0, np.float32(1), np.float32(-1))
1472
+ signs = signs.reshape((n_blocks, -1, 4, 8))
1473
+
1474
+ qh = qh.reshape((n_blocks, -1, 1)) >> np.array(
1475
+ [i for i in range(8)], dtype=np.uint8
1476
+ )
1477
+ qh = (qh & 0x01).astype(np.uint16).reshape((n_blocks, -1))
1478
+ qs = qs.astype(np.uint16) | (qh << 8)
1479
+
1480
+ assert cls.grid is not None
1481
+ grid = np.take_along_axis(cls.grid, qs.reshape((n_blocks, -1, 1, 1)), axis=-2)
1482
+ grid = grid.reshape((n_blocks, -1, 4, 8))
1483
+
1484
+ return (db * grid * signs).reshape((n_blocks, -1))
1485
+
1486
+
1487
+ class IQ1_S(__Quant, qtype=GGMLQuantizationType.IQ1_S):
1488
+ # iq1s_grid, with each byte packed into 2 bits
1489
+ # -1, 0, 1 <=> 0, 1, 2
1490
+ grid_shape = (2048, 8)
1491
+ grid_map = (-1, 0, 1)
1492
+ grid_hex = (
1493
+ b"00000200050008000a00110015002000220028002a0045005100540056006500"
1494
+ b"8000820088008a009500a000a200a800aa000401050111011401160119011a01"
1495
+ b"2501410146014901520155015a0161016401660168018501910194019601a501"
1496
+ b"0002020208020a0215022002220228022a024502510259026402690280028202"
1497
+ b"88028a02910295029902a002a202a802aa021104140416042504410449045504"
1498
+ b"5a046404650491049904a5040105040505050605150518051a05290540054505"
1499
+ b"4a0550055105540555055605590560056205650568056a058105910595059805"
1500
+ b"9a05a105a405a505a605a9051406190641064406500652065506580660066106"
1501
+ b"6606690685069106940699060008020808080a0815082008220828082a084508"
1502
+ b"5108560865088008820888088a089508a008a208a808aa080509110914091909"
1503
+ b"2409250941095009510955096109640969099109940996099909a509000a020a"
1504
+ b"080a0a0a150a200a220a280a2a0a450a510a590a610a650a800a820a850a880a"
1505
+ b"8a0a950aa00aa20aa80aaa0a1010111014101910241025104110441050105510"
1506
+ b"58106110641065106910911094109610a110a510011104110611091110111211"
1507
+ b"1511181121112411291145114a11501151115211541155115611591160116511"
1508
+ b"841192119511a111a41111121412161225124012461249125212551258125a12"
1509
+ b"641266128512911294129612a512011406140914141415141814191421142614"
1510
+ b"41144514461448144a1451145414551456145914621465146814841489149014"
1511
+ b"94149514981499149a14a114a414a514a914021505150a151115141515151615"
1512
+ b"191520152215251528152a154115441545154615511552155415551556155915"
1513
+ b"5a1561156415651566156915801582158415851588158a159015911594159515"
1514
+ b"961599159a15a015a215a51501160416051606161516161618161a1621162616"
1515
+ b"401642164416451648164a165116551656165816591661166416651668166916"
1516
+ b"6a1686168a1692169516a416a916111816182518411844184618491850185518"
1517
+ b"58185a1860186118641866186918851891189418a5181019121915191a192119"
1518
+ b"25194219441945194819511954195519561959195a19601965196a1989199119"
1519
+ b"921995199819a119a619a919091a161a241a261a441a461a491a501a521a551a"
1520
+ b"581a611a661a691a851a911a961a9a1a0020022008200a201520202022202520"
1521
+ b"28202a20452051205920612065208020822088208a209520a020a220a520a820"
1522
+ b"aa2005211121142119212521422144214921552158215a216121642165216621"
1523
+ b"8521902196219921a521012208220a22112215222022222228222a2245225122"
1524
+ b"562259226522812288228a2291229522a022a222a822aa220524142416241924"
1525
+ b"252444244524462449245224552458245a2466248524912494249924a124a524"
1526
+ b"0925152521252925402545254825512554255525592562256525682589259025"
1527
+ b"9425952598259a25a125a425a625a92505261026122619262526412649265526"
1528
+ b"6026612669268426862690269a260028022808280a2815282028222828282a28"
1529
+ b"45285128542865288028822888288a28a028a228a828aa280929112914291929"
1530
+ b"2529462949295229552961296429662969298529902996299929a429a529002a"
1531
+ b"022a082a0a2a202a222a282a2a2a452a512a562a592a652a802a822a882a8a2a"
1532
+ b"952aa02aa22aa82aaa2a054011401640254049405240554058405a4061406440"
1533
+ b"664094409940a140a6400041014104410641094112411541164118411a412141"
1534
+ b"26412941454148414a41514154415541564159415a41654168416a4181418441"
1535
+ b"8641904192419541a041a141a241054211421442164225424142524255425a42"
1536
+ b"6442694289429442a5420144154419442944454448444a445144544455445644"
1537
+ b"61446244654468446a44814486448944904492449544a044a144a94401450245"
1538
+ b"05450a4511451445154516451945204525452a45414544454545464549455045"
1539
+ b"5145544555455645584559456145644565456645694582458445854588459145"
1540
+ b"94459545964599459a45a545a845aa450146054609461446154618461a462146"
1541
+ b"2446294640464246454648465046514652465546564659466246654668468146"
1542
+ b"85468a4694469546a146a446a6460548114815481a4825484248494850485548"
1543
+ b"5848614864486648694885489148944896489948a5480149054906490a491049"
1544
+ b"144915491849214924492649404945494a495149524954495549564959496049"
1545
+ b"6249654966496a49864989499249954996499849a149a449a649a949164a444a"
1546
+ b"464a494a554a584a5a4a644a694a944aa54a0150045005500650095012501550"
1547
+ b"1a50215024502950405045504850515054505550565059506550685086508950"
1548
+ b"95509850a050a150a650a9500551085109510a51115114511551165118511951"
1549
+ b"20512551265128512a5141514451455146514951505151515251545155515651"
1550
+ b"585159515a51615164516551665169518251855191519451955196519951a051"
1551
+ b"a551aa5101520652125215521a5221522452425245524a525152545255525652"
1552
+ b"595262526552855290529252955299529a52a452045405541154145415541654"
1553
+ b"185419542154255428542a54415444544554465449544a545054515454545554"
1554
+ b"5654585459545a54615462546454655466546954805488548a54915494549554"
1555
+ b"96549954a154a454a554aa540155025504550555065509551055115512551455"
1556
+ b"1555165519551a55215524552555265529554055415542554455455546554855"
1557
+ b"4955505551555255545555555655585559555a55605561556455655566556855"
1558
+ b"69556a5581558455855589558a559055915594559555965598559955a155a455"
1559
+ b"a555a655a9550056015602560456065608560956115614561556185619562056"
1560
+ b"2156225624562556265628562956415645564656485649564a56505651565256"
1561
+ b"545655565656585659565a566156645665566956825685568656885689568a56"
1562
+ b"915695569a56a256a556a656a856a95604580558065809581058155818582158"
1563
+ b"2a58455848584a58515854585558565858585958605862586458655882588958"
1564
+ b"9058925895589858a158a9580159025905590a59115914591559165919592559"
1565
+ b"41594459455946594959505951595259545955595659585959595a5961596459"
1566
+ b"655966596959815985598959915994599559965998599959a559045a085a155a"
1567
+ b"1a5a205a255a265a295a455a485a495a515a555a565a585a595a625a655a685a"
1568
+ b"6a5a815a8a5a925a955a965a985a9a5aa15a0560146016601960256044605060"
1569
+ b"5560566058605a60616064606660696081609660a56001610461066109611261"
1570
+ b"15612161226126612961456149615161556156615961656166616a6184618a61"
1571
+ b"92619561a161a661a96111621662196240624162466255625662586260628562"
1572
+ b"91629662a56211641264156416641a6421642664296440644264456448644a64"
1573
+ b"516454645564566459645a646064626465648464856489649064926494649564"
1574
+ b"966498649a64a164a464a964056508650a651165156516651965446545654665"
1575
+ b"496550655165546555655665596561656465656566656965866589658a659165"
1576
+ b"9565966599659a65a265a565a665a86502660966156620662666286629664066"
1577
+ b"456648664a66516654665566566658665a666066656668668066826685668a66"
1578
+ b"9466966698669966a066a466a666aa661668196825684168526855685a686168"
1579
+ b"6968856891689868a66801690469106915692169246926692969406941694569"
1580
+ b"4669486951695469556956695969606965696a69826984698a699569a169a469"
1581
+ b"a569a969116a166a186a416a446a496a506a556a586a5a6a646a656a696a866a"
1582
+ b"946a986a9a6aa66a0080028008800a802080228028802a804580508051805480"
1583
+ b"5680598065808080828088808a809580a080a280a880aa800581118114811681"
1584
+ b"1981258141814481498150815281558156815881598164816681698185818981"
1585
+ b"948196819981a5810082028208820a8215822082228228822a82518254825982"
1586
+ b"65828082828288828a829582a082a282a882aa82148419844184448451845584"
1587
+ b"5a846184648469849484998401850985128515851a8526852985408541854585"
1588
+ b"4885518554855585568559855a856585668568856a8581858485868589859085"
1589
+ b"928595859885a68511861686198625864186448649864a865086558659865a86"
1590
+ b"618666866a86858691869a86a4860088028808880a8815882088228828882a88"
1591
+ b"41884588518854885988658869888088828888888a889588a088a288a888aa88"
1592
+ b"05890689118914891689258941894489468949895089528955895a8961896489"
1593
+ b"858996899989a589008a028a088a0a8a158a208a228a288a2a8a458a518a548a"
1594
+ b"568a808a828a888a8a8a958aa08aa28aa88aaa8a059011901690189019902590"
1595
+ b"419046904990559058905a9069906a9085909190949096909990a59001910491"
1596
+ b"069109911091159118911a912191249126912991409145915091519154915591"
1597
+ b"569159916291659184918691929195919891a191a491a691a991059211921492"
1598
+ b"19922592449246924992509252925592589266926992859294929692a9920194"
1599
+ b"04940694109415941894269440944a9451945494559456945894599460946194"
1600
+ b"62946594849486949294949495949894a194a9940095059508950a9510951195"
1601
+ b"14951595169519952195259529952a9541954495459546954995509551955295"
1602
+ b"549555955695589559955a956195649565956695699581958595889591959295"
1603
+ b"94959595969599959a95a095a295a595a895aa95019604961096159619962096"
1604
+ b"2696299645964896499651965296559656965996659668968296849689968a96"
1605
+ b"929694969596a496a696a9960598169819982598419846985098529855985698"
1606
+ b"5a98649865988598919896989998a59804990699099910991299159918991a99"
1607
+ b"209921992499269940994299459948994a995199549955995699599962996599"
1608
+ b"66996a99819984999099929995999a99a199a699059a159a259a449a469a499a"
1609
+ b"509a559a589a619a859a919a949a959a969a00a002a008a00aa015a020a022a0"
1610
+ b"28a02aa045a051a054a056a059a080a082a088a08aa095a0a0a0a2a0a8a0aaa0"
1611
+ b"05a109a111a114a116a119a11aa146a149a151a155a158a15aa161a164a185a1"
1612
+ b"90a192a196a199a102a208a20aa210a219a222a228a22aa245a251a256a259a2"
1613
+ b"65a280a282a288a28aa295a2a0a2a2a2a8a2aaa219a425a441a444a450a454a4"
1614
+ b"55a458a45aa461a465a466a468a469a485a406a509a510a512a515a518a526a5"
1615
+ b"29a542a545a551a554a555a556a559a565a56aa581a584a585a586a589a592a5"
1616
+ b"95a598a505a611a616a61aa621a625a644a646a64aa652a655a656a658a660a6"
1617
+ b"62a686a690a695a696a699a6a1a6a4a6a6a600a802a808a80aa820a822a828a8"
1618
+ b"2aa851a854a856a859a880a882a888a88aa895a8a0a8a2a8a8a8aaa805a914a9"
1619
+ b"19a921a925a941a950a955a95aa961a966a969a990a996a900aa02aa08aa0aaa"
1620
+ b"20aa22aa28aa2aaa51aa54aa56aa80aa82aa88aa8aaa95aaa0aaa2aaa8aaaaaa"
1621
+ )
1622
+
1623
+ delta = np.float32(0.125)
1624
+
1625
+ @classmethod
1626
+ def dequantize_blocks(cls, blocks: np.ndarray) -> np.ndarray:
1627
+ n_blocks = blocks.shape[0]
1628
+
1629
+ d, rest = np.hsplit(blocks, [2])
1630
+ qs, qh = np.hsplit(rest, [QK_K // 8])
1631
+
1632
+ d = d.view(np.float16).astype(np.float32)
1633
+ qh = qh.view(np.uint16)
1634
+
1635
+ dl = d * (2 * ((qh >> 12) & 7) + 1)
1636
+ dl = dl.reshape((n_blocks, -1, 1, 1))
1637
+ delta = np.where((qh & np.uint16(0x8000)) == 0, cls.delta, -cls.delta)
1638
+ delta = delta.reshape((n_blocks, -1, 1, 1))
1639
+
1640
+ qh = qh.reshape((n_blocks, -1, 1)) >> np.array(
1641
+ [0, 3, 6, 9], dtype=np.uint16
1642
+ ).reshape((1, 1, 4))
1643
+ qs = qs.astype(np.uint16) | ((qh & 7) << 8).reshape((n_blocks, -1))
1644
+
1645
+ assert cls.grid is not None
1646
+ grid = np.take_along_axis(cls.grid, qs.reshape((n_blocks, -1, 1, 1)), axis=-2)
1647
+ grid = grid.reshape((n_blocks, -1, 4, 8))
1648
+
1649
+ return (dl * (grid + delta)).reshape((n_blocks, -1))
1650
+
1651
+
1652
+ class IQ1_M(__Quant, qtype=GGMLQuantizationType.IQ1_M):
1653
+ grid_shape = IQ1_S.grid_shape
1654
+ grid_map = IQ1_S.grid_map
1655
+ grid_hex = IQ1_S.grid_hex
1656
+
1657
+ delta = IQ1_S.delta
1658
+
1659
+ # Okay *this* type is weird. It's the only one which stores the f16 scales in multiple parts.
1660
+ @classmethod
1661
+ def dequantize_blocks(cls, blocks: np.ndarray) -> np.ndarray:
1662
+ n_blocks = blocks.shape[0]
1663
+
1664
+ qs, rest = np.hsplit(blocks, [QK_K // 8])
1665
+ qh, scales = np.hsplit(rest, [QK_K // 16])
1666
+
1667
+ # The f16 scale is packed across multiple bytes
1668
+ scales = scales.view(np.uint16)
1669
+ d = (scales.reshape((n_blocks, 4)) & np.uint16(0xF000)) >> np.array(
1670
+ [12, 8, 4, 0], dtype=np.uint16
1671
+ ).reshape((1, 4))
1672
+ d = d[..., 0] | d[..., 1] | d[..., 2] | d[..., 3]
1673
+ d = d.view(np.float16).astype(np.float32).reshape((n_blocks, 1))
1674
+
1675
+ scales = scales.reshape(n_blocks, -1, 1) >> np.array(
1676
+ [0, 3, 6, 9], dtype=np.uint16
1677
+ ).reshape((1, 1, 4))
1678
+ scales = (scales & 0x07).reshape((n_blocks, -1))
1679
+ dl = d * (2 * scales + 1)
1680
+ dl = dl.reshape((n_blocks, -1, 2, 1, 1))
1681
+
1682
+ qh = qh.reshape((n_blocks, -1, 1)) >> np.array([0, 4], dtype=np.uint8).reshape(
1683
+ (1, 1, 2)
1684
+ )
1685
+ qs = qs.astype(np.uint16) | ((qh & 0x07).astype(np.uint16) << 8).reshape(
1686
+ (n_blocks, -1)
1687
+ )
1688
+
1689
+ delta = np.where(qh & 0x08 == 0, cls.delta, -cls.delta)
1690
+ delta = delta.reshape((n_blocks, -1, 2, 2, 1))
1691
+
1692
+ assert cls.grid is not None
1693
+ grid = np.take_along_axis(cls.grid, qs.reshape((n_blocks, -1, 1, 1)), axis=-2)
1694
+ grid = grid.reshape((n_blocks, -1, 2, 2, 8))
1695
+
1696
+ return (dl * (grid + delta)).reshape((n_blocks, -1))
1697
+
1698
+
1699
+ class IQ4_NL(__Quant, qtype=GGMLQuantizationType.IQ4_NL):
1700
+ kvalues = (-127, -104, -83, -65, -49, -35, -22, -10, 1, 13, 25, 38, 53, 69, 89, 113)
1701
+
1702
+ @classmethod
1703
+ def dequantize_blocks(cls, blocks: np.ndarray) -> np.ndarray:
1704
+ n_blocks = blocks.shape[0]
1705
+
1706
+ d, qs = np.hsplit(blocks, [2])
1707
+
1708
+ d = d.view(np.float16).astype(np.float32)
1709
+
1710
+ qs = qs.reshape((n_blocks, -1, 1, cls.block_size // 2)) >> np.array(
1711
+ [0, 4], dtype=np.uint8
1712
+ ).reshape((1, 1, 2, 1))
1713
+
1714
+ qs = (qs & np.uint8(0x0F)).reshape((n_blocks, -1, 1))
1715
+
1716
+ kvalues = np.array(cls.kvalues, dtype=np.int8).reshape(1, 1, 16)
1717
+ qs = (
1718
+ np.take_along_axis(kvalues, qs, axis=-1)
1719
+ .astype(np.float32)
1720
+ .reshape((n_blocks, -1))
1721
+ )
1722
+
1723
+ return d * qs
1724
+
1725
+
1726
+ class IQ4_XS(__Quant, qtype=GGMLQuantizationType.IQ4_XS):
1727
+ @classmethod
1728
+ def dequantize_blocks(cls, blocks: np.ndarray) -> np.ndarray:
1729
+ n_blocks = blocks.shape[0]
1730
+
1731
+ d, rest = np.hsplit(blocks, [2])
1732
+ scales_h, rest = np.hsplit(rest, [2])
1733
+ scales_l, qs = np.hsplit(rest, [QK_K // 64])
1734
+
1735
+ d = d.view(np.float16).astype(np.float32)
1736
+ scales_h = scales_h.view(np.uint16)
1737
+
1738
+ scales_l = scales_l.reshape((n_blocks, -1, 1)) >> np.array(
1739
+ [0, 4], dtype=np.uint8
1740
+ ).reshape((1, 1, 2))
1741
+ scales_h = scales_h.reshape((n_blocks, 1, -1)) >> np.array(
1742
+ [2 * i for i in range(QK_K // 32)], dtype=np.uint16
1743
+ ).reshape((1, -1, 1))
1744
+ scales_l = scales_l.reshape((n_blocks, -1)) & np.uint8(0x0F)
1745
+ scales_h = scales_h.reshape((n_blocks, -1)).astype(np.uint8) & np.uint8(0x03)
1746
+
1747
+ scales = (scales_l | (scales_h << np.uint8(4))).astype(np.int8) - np.int8(32)
1748
+ dl = (d * scales.astype(np.float32)).reshape((n_blocks, -1, 1))
1749
+
1750
+ qs = qs.reshape((n_blocks, -1, 1, 16)) >> np.array(
1751
+ [0, 4], dtype=np.uint8
1752
+ ).reshape((1, 1, 2, 1))
1753
+ qs = qs.reshape((n_blocks, -1, 32, 1)) & np.uint8(0x0F)
1754
+
1755
+ kvalues = np.array(IQ4_NL.kvalues, dtype=np.int8).reshape((1, 1, 1, -1))
1756
+ qs = (
1757
+ np.take_along_axis(kvalues, qs, axis=-1)
1758
+ .astype(np.float32)
1759
+ .reshape((n_blocks, -1, 32))
1760
+ )
1761
+
1762
+ return (dl * qs).reshape((n_blocks, -1))
modules_forge/packages/gguf/quick_4bits_ops.py ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # By Forge
2
+
3
+
4
+ import torch
5
+
6
+
7
+ def native_unpack_4x4bits_in_1x16bits_to_4x8bits_in_1x32bits(x):
8
+ x = x.view(torch.uint8).view(x.size(0), -1)
9
+ unpacked = torch.stack([x & 15, x >> 4], dim=-1)
10
+ reshaped = unpacked.view(x.size(0), -1)
11
+ reshaped = reshaped.view(torch.int8) - 8
12
+ return reshaped.view(torch.int32)
13
+
14
+
15
+ def native_unpack_4x4bits_in_1x16bits_to_4x8bits_in_1x32bits_u(x):
16
+ x = x.view(torch.uint8).view(x.size(0), -1)
17
+ unpacked = torch.stack([x & 15, x >> 4], dim=-1)
18
+ reshaped = unpacked.view(x.size(0), -1)
19
+ return reshaped.view(torch.int32)
20
+
21
+
22
+ disable_all_optimizations = False
23
+
24
+ if not hasattr(torch, "uint16"):
25
+ disable_all_optimizations = True
26
+
27
+ if disable_all_optimizations:
28
+ print(
29
+ "You are using PyTorch below version 2.3. Some optimizations will be disabled."
30
+ )
31
+
32
+ if not disable_all_optimizations:
33
+ native_4bits_lookup_table = (
34
+ native_unpack_4x4bits_in_1x16bits_to_4x8bits_in_1x32bits(
35
+ torch.arange(start=0, end=256 * 256, dtype=torch.long).to(torch.uint16)
36
+ )[:, 0]
37
+ )
38
+ native_4bits_lookup_table_u = (
39
+ native_unpack_4x4bits_in_1x16bits_to_4x8bits_in_1x32bits_u(
40
+ torch.arange(start=0, end=256 * 256, dtype=torch.long).to(torch.uint16)
41
+ )[:, 0]
42
+ )
43
+
44
+
45
+ def quick_unpack_4bits(x):
46
+ if disable_all_optimizations:
47
+ return (
48
+ torch.stack([x & 15, x >> 4], dim=-1).view(x.size(0), -1).view(torch.int8)
49
+ - 8
50
+ )
51
+
52
+ global native_4bits_lookup_table
53
+
54
+ s0 = x.size(0)
55
+ x = x.view(torch.uint16)
56
+
57
+ if native_4bits_lookup_table.device != x.device:
58
+ native_4bits_lookup_table = native_4bits_lookup_table.to(device=x.device)
59
+
60
+ y = torch.index_select(
61
+ input=native_4bits_lookup_table, dim=0, index=x.to(dtype=torch.int32).flatten()
62
+ )
63
+ y = y.view(torch.int8)
64
+ y = y.view(s0, -1)
65
+
66
+ return y
67
+
68
+
69
+ def quick_unpack_4bits_u(x):
70
+ if disable_all_optimizations:
71
+ return torch.stack([x & 15, x >> 4], dim=-1).view(x.size(0), -1)
72
+
73
+ global native_4bits_lookup_table_u
74
+
75
+ s0 = x.size(0)
76
+ x = x.view(torch.uint16)
77
+
78
+ if native_4bits_lookup_table_u.device != x.device:
79
+ native_4bits_lookup_table_u = native_4bits_lookup_table_u.to(device=x.device)
80
+
81
+ y = torch.index_select(
82
+ input=native_4bits_lookup_table_u,
83
+ dim=0,
84
+ index=x.to(dtype=torch.int32).flatten(),
85
+ )
86
+ y = y.view(torch.uint8)
87
+ y = y.view(s0, -1)
88
+
89
+ return y
90
+
91
+
92
+ def change_4bits_order(x):
93
+ y = torch.stack([x & 15, x >> 4], dim=-2).view(x.size(0), -1)
94
+ z = y[:, ::2] | (y[:, 1::2] << 4)
95
+ return z
modules_forge/packages/gguf/tensor_mapping.py ADDED
@@ -0,0 +1,540 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from typing import Sequence
4
+
5
+ from .constants import MODEL_ARCH, MODEL_TENSOR, MODEL_TENSORS, TENSOR_NAMES
6
+
7
+
8
+ class TensorNameMap:
9
+ mappings_cfg: dict[MODEL_TENSOR, tuple[str, ...]] = {
10
+ # Token embeddings
11
+ MODEL_TENSOR.TOKEN_EMBD: (
12
+ "gpt_neox.embed_in", # gptneox
13
+ "transformer.wte", # gpt2 gpt-j mpt refact qwen dbrx jais
14
+ "transformer.word_embeddings", # falcon
15
+ "word_embeddings", # bloom
16
+ "model.embed_tokens", # llama-hf
17
+ "tok_embeddings", # llama-pth
18
+ "embeddings.word_embeddings", # bert nomic-bert
19
+ "language_model.embedding.word_embeddings", # persimmon
20
+ "wte", # gpt2
21
+ "transformer.embd.wte", # phi2
22
+ "model.tok_embeddings", # internlm2
23
+ "model.embedding", # mamba-qbert
24
+ "backbone.embedding", # mamba
25
+ "backbone.embeddings", # mamba-hf
26
+ "transformer.in_out_embed", # Grok
27
+ "embedding.word_embeddings", # chatglm
28
+ "transformer.token_embeddings", # openelm
29
+ "shared", # t5
30
+ ),
31
+ # Token type embeddings
32
+ MODEL_TENSOR.TOKEN_TYPES: (
33
+ "embeddings.token_type_embeddings", # bert nomic-bert
34
+ ),
35
+ # Normalization of token embeddings
36
+ MODEL_TENSOR.TOKEN_EMBD_NORM: (
37
+ "word_embeddings_layernorm", # bloom
38
+ "embeddings.LayerNorm", # bert
39
+ "emb_ln", # nomic-bert
40
+ "transformer.norm", # openelm
41
+ ),
42
+ # Position embeddings
43
+ MODEL_TENSOR.POS_EMBD: (
44
+ "transformer.wpe", # gpt2
45
+ "embeddings.position_embeddings", # bert
46
+ "wpe", # gpt2
47
+ ),
48
+ # Output
49
+ MODEL_TENSOR.OUTPUT: (
50
+ "embed_out", # gptneox
51
+ "lm_head", # gpt2 mpt falcon llama-hf baichuan qwen mamba dbrx jais
52
+ "output", # llama-pth bloom internlm2
53
+ "word_embeddings_for_head", # persimmon
54
+ "lm_head.linear", # phi2
55
+ "output_layer", # chatglm
56
+ ),
57
+ # Output norm
58
+ MODEL_TENSOR.OUTPUT_NORM: (
59
+ "gpt_neox.final_layer_norm", # gptneox
60
+ "transformer.ln_f", # gpt2 gpt-j falcon jais
61
+ "model.norm", # llama-hf baichuan internlm2
62
+ "norm", # llama-pth
63
+ "transformer.norm_f", # mpt dbrx
64
+ "ln_f", # refact bloom qwen gpt2
65
+ "language_model.encoder.final_layernorm", # persimmon
66
+ "model.final_layernorm", # persimmon
67
+ "lm_head.ln", # phi2
68
+ "model.norm_f", # mamba-qbert
69
+ "backbone.norm_f", # mamba
70
+ "transformer.rms_norm", # Grok
71
+ "encoder.final_layernorm", # chatglm
72
+ "transformer.norm", # openelm
73
+ ),
74
+ # Rope frequencies
75
+ MODEL_TENSOR.ROPE_FREQS: (
76
+ "rope.freqs", # llama-pth
77
+ "rotary_pos_emb.inv_freq", # chatglm
78
+ ),
79
+ }
80
+
81
+ block_mappings_cfg: dict[MODEL_TENSOR, tuple[str, ...]] = {
82
+ # Attention norm
83
+ MODEL_TENSOR.ATTN_NORM: (
84
+ "gpt_neox.layers.{bid}.input_layernorm", # gptneox
85
+ "transformer.h.{bid}.ln_1", # gpt2 gpt-j refact qwen jais
86
+ "transformer.blocks.{bid}.norm_1", # mpt
87
+ "transformer.h.{bid}.input_layernorm", # falcon7b
88
+ "h.{bid}.input_layernorm", # bloom
89
+ "transformer.h.{bid}.ln_mlp", # falcon40b
90
+ "model.layers.{bid}.input_layernorm", # llama-hf
91
+ "layers.{bid}.attention_norm", # llama-pth
92
+ "language_model.encoder.layers.{bid}.input_layernorm", # persimmon
93
+ "model.layers.{bid}.ln1", # yi
94
+ "h.{bid}.ln_1", # gpt2
95
+ "transformer.h.{bid}.ln", # phi2
96
+ "model.layers.layers.{bid}.norm", # plamo
97
+ "model.layers.{bid}.attention_norm", # internlm2
98
+ "model.layers.{bid}.norm", # mamba-qbert
99
+ "backbone.layers.{bid}.norm", # mamba
100
+ "transformer.decoder_layer.{bid}.rms_norm", # Grok
101
+ "transformer.blocks.{bid}.norm_attn_norm.norm_1", # dbrx
102
+ "encoder.layers.{bid}.input_layernorm", # chatglm
103
+ "transformer.layers.{bid}.attn_norm", # openelm
104
+ ),
105
+ # Attention norm 2
106
+ MODEL_TENSOR.ATTN_NORM_2: (
107
+ "transformer.h.{bid}.ln_attn", # falcon40b
108
+ "encoder.layer.{bid}.layer_norm_1", # jina-v2-code
109
+ ),
110
+ # Attention query-key-value
111
+ MODEL_TENSOR.ATTN_QKV: (
112
+ "gpt_neox.layers.{bid}.attention.query_key_value", # gptneox
113
+ "transformer.h.{bid}.attn.c_attn", # gpt2 qwen jais
114
+ "transformer.blocks.{bid}.attn.Wqkv", # mpt
115
+ "transformer.blocks.{bid}.norm_attn_norm.attn.Wqkv", # dbrx
116
+ "transformer.h.{bid}.self_attention.query_key_value", # falcon
117
+ "h.{bid}.self_attention.query_key_value", # bloom
118
+ "language_model.encoder.layers.{bid}.self_attention.query_key_value", # persimmon
119
+ "model.layers.{bid}.self_attn.query_key_value", # persimmon
120
+ "h.{bid}.attn.c_attn", # gpt2
121
+ "transformer.h.{bid}.mixer.Wqkv", # phi2
122
+ "encoder.layers.{bid}.attn.Wqkv", # nomic-bert
123
+ "model.layers.{bid}.self_attn.qkv_proj", # phi3
124
+ "encoder.layers.{bid}.self_attention.query_key_value", # chatglm
125
+ "transformer.layers.{bid}.attn.qkv_proj", # openelm
126
+ ),
127
+ # Attention query
128
+ MODEL_TENSOR.ATTN_Q: (
129
+ "model.layers.{bid}.self_attn.q_proj", # llama-hf
130
+ "layers.{bid}.attention.wq", # llama-pth
131
+ "encoder.layer.{bid}.attention.self.query", # bert
132
+ "transformer.h.{bid}.attn.q_proj", # gpt-j
133
+ "model.layers.layers.{bid}.self_attn.q_proj", # plamo
134
+ "model.layers.{bid}.attention.wq", # internlm2
135
+ "transformer.decoder_layer.{bid}.multi_head_attention.query", # Grok
136
+ ),
137
+ # Attention key
138
+ MODEL_TENSOR.ATTN_K: (
139
+ "model.layers.{bid}.self_attn.k_proj", # llama-hf
140
+ "layers.{bid}.attention.wk", # llama-pth
141
+ "encoder.layer.{bid}.attention.self.key", # bert
142
+ "transformer.h.{bid}.attn.k_proj", # gpt-j
143
+ "transformer.h.{bid}.attn.k", # refact
144
+ "model.layers.layers.{bid}.self_attn.k_proj", # plamo
145
+ "model.layers.{bid}.attention.wk", # internlm2
146
+ "transformer.decoder_layer.{bid}.multi_head_attention.key", # Grok
147
+ ),
148
+ # Attention value
149
+ MODEL_TENSOR.ATTN_V: (
150
+ "model.layers.{bid}.self_attn.v_proj", # llama-hf
151
+ "layers.{bid}.attention.wv", # llama-pth
152
+ "encoder.layer.{bid}.attention.self.value", # bert
153
+ "transformer.h.{bid}.attn.v_proj", # gpt-j
154
+ "transformer.h.{bid}.attn.v", # refact
155
+ "model.layers.layers.{bid}.self_attn.v_proj", # plamo
156
+ "model.layers.{bid}.attention.wv", # internlm2
157
+ "transformer.decoder_layer.{bid}.multi_head_attention.value", # Grok
158
+ ),
159
+ # Attention output
160
+ MODEL_TENSOR.ATTN_OUT: (
161
+ "gpt_neox.layers.{bid}.attention.dense", # gptneox
162
+ "transformer.h.{bid}.attn.c_proj", # gpt2 refact qwen jais
163
+ "transformer.blocks.{bid}.attn.out_proj", # mpt
164
+ "transformer.h.{bid}.self_attention.dense", # falcon
165
+ "h.{bid}.self_attention.dense", # bloom
166
+ "model.layers.{bid}.self_attn.o_proj", # llama-hf
167
+ "layers.{bid}.attention.wo", # llama-pth
168
+ "encoder.layer.{bid}.attention.output.dense", # bert
169
+ "transformer.h.{bid}.attn.out_proj", # gpt-j
170
+ "language_model.encoder.layers.{bid}.self_attention.dense", # persimmon
171
+ "model.layers.{bid}.self_attn.dense", # persimmon
172
+ "h.{bid}.attn.c_proj", # gpt2
173
+ "transformer.h.{bid}.mixer.out_proj", # phi2
174
+ "model.layers.layers.{bid}.self_attn.o_proj", # plamo
175
+ "model.layers.{bid}.attention.wo", # internlm2
176
+ "encoder.layers.{bid}.attn.out_proj", # nomic-bert
177
+ "transformer.decoder_layer.{bid}.multi_head_attention.linear", # Grok
178
+ "transformer.blocks.{bid}.norm_attn_norm.attn.out_proj", # dbrx
179
+ "encoder.layers.{bid}.self_attention.dense", # chatglm
180
+ "transformer.layers.{bid}.attn.out_proj", # openelm
181
+ ),
182
+ # Attention output norm
183
+ MODEL_TENSOR.ATTN_OUT_NORM: (
184
+ "encoder.layer.{bid}.attention.output.LayerNorm", # bert
185
+ "encoder.layers.{bid}.norm1", # nomic-bert
186
+ "transformer.decoder_layer.{bid}.rms_norm_1", # Grok
187
+ "transformer.blocks.{bid}.norm_attn_norm.norm_2", # dbrx
188
+ ),
189
+ MODEL_TENSOR.ATTN_POST_NORM: (
190
+ "model.layers.{bid}.post_attention_layernorm", # gemma2
191
+ ),
192
+ # Rotary embeddings
193
+ MODEL_TENSOR.ATTN_ROT_EMBD: (
194
+ "model.layers.{bid}.self_attn.rotary_emb.inv_freq", # llama-hf
195
+ "layers.{bid}.attention.inner_attention.rope.freqs", # llama-pth
196
+ "model.layers.layers.{bid}.self_attn.rotary_emb.inv_freq", # plamo
197
+ "transformer.h.{bid}.attn.rotary_emb.inv_freq", # codeshell
198
+ ),
199
+ # Feed-forward norm
200
+ MODEL_TENSOR.FFN_NORM: (
201
+ "gpt_neox.layers.{bid}.post_attention_layernorm", # gptneox
202
+ "transformer.h.{bid}.ln_2", # gpt2 refact qwen jais
203
+ "h.{bid}.post_attention_layernorm", # bloom
204
+ "transformer.blocks.{bid}.norm_2", # mpt
205
+ "model.layers.{bid}.post_attention_layernorm", # llama-hf
206
+ "layers.{bid}.ffn_norm", # llama-pth
207
+ "language_model.encoder.layers.{bid}.post_attention_layernorm", # persimmon
208
+ "model.layers.{bid}.ln2", # yi
209
+ "h.{bid}.ln_2", # gpt2
210
+ "model.layers.{bid}.ffn_norm", # internlm2
211
+ "transformer.decoder_layer.{bid}.rms_norm_2", # Grok
212
+ "encoder.layers.{bid}.post_attention_layernorm", # chatglm
213
+ "transformer.layers.{bid}.ffn_norm", # openelm
214
+ ),
215
+ # Post feed-forward norm
216
+ MODEL_TENSOR.FFN_PRE_NORM: (
217
+ "model.layers.{bid}.pre_feedforward_layernorm", # gemma2
218
+ ),
219
+ # Post feed-forward norm
220
+ MODEL_TENSOR.FFN_POST_NORM: (
221
+ "model.layers.{bid}.post_feedforward_layernorm", # gemma2
222
+ ),
223
+ MODEL_TENSOR.FFN_GATE_INP: (
224
+ "layers.{bid}.feed_forward.gate", # mixtral
225
+ "model.layers.{bid}.block_sparse_moe.gate", # mixtral
226
+ "model.layers.{bid}.mlp.gate", # qwen2moe
227
+ "transformer.decoder_layer.{bid}.router", # Grok
228
+ "transformer.blocks.{bid}.ffn.router.layer", # dbrx
229
+ ),
230
+ MODEL_TENSOR.FFN_GATE_INP_SHEXP: (
231
+ "model.layers.{bid}.mlp.shared_expert_gate", # qwen2moe
232
+ ),
233
+ # Feed-forward up
234
+ MODEL_TENSOR.FFN_UP: (
235
+ "gpt_neox.layers.{bid}.mlp.dense_h_to_4h", # gptneox
236
+ "transformer.h.{bid}.mlp.c_fc", # gpt2 jais
237
+ "transformer.blocks.{bid}.ffn.up_proj", # mpt
238
+ "transformer.h.{bid}.mlp.dense_h_to_4h", # falcon
239
+ "h.{bid}.mlp.dense_h_to_4h", # bloom
240
+ "model.layers.{bid}.mlp.up_proj", # llama-hf refact
241
+ "layers.{bid}.feed_forward.w3", # llama-pth
242
+ "encoder.layer.{bid}.intermediate.dense", # bert
243
+ "transformer.h.{bid}.mlp.fc_in", # gpt-j
244
+ "transformer.h.{bid}.mlp.linear_3", # refact
245
+ "language_model.encoder.layers.{bid}.mlp.dense_h_to_4h", # persimmon
246
+ "model.layers.{bid}.mlp.dense_h_to_4h", # persimmon
247
+ "transformer.h.{bid}.mlp.w1", # qwen
248
+ "h.{bid}.mlp.c_fc", # gpt2
249
+ "transformer.h.{bid}.mlp.fc1", # phi2
250
+ "model.layers.{bid}.mlp.fc1", # phi2
251
+ "model.layers.{bid}.mlp.gate_up_proj", # phi3
252
+ "model.layers.layers.{bid}.mlp.up_proj", # plamo
253
+ "model.layers.{bid}.feed_forward.w3", # internlm2
254
+ "encoder.layers.{bid}.mlp.fc11", # nomic-bert
255
+ "model.layers.{bid}.mlp.c_fc", # starcoder2
256
+ "encoder.layer.{bid}.mlp.gated_layers_v", # jina-bert-v2
257
+ "model.layers.{bid}.residual_mlp.w3", # arctic
258
+ "encoder.layers.{bid}.mlp.dense_h_to_4h", # chatglm
259
+ ),
260
+ MODEL_TENSOR.FFN_UP_EXP: (
261
+ "layers.{bid}.feed_forward.experts.w3", # mixtral (merged)
262
+ "transformer.decoder_layer.{bid}.moe.linear_v", # Grok (merged)
263
+ "transformer.blocks.{bid}.ffn.experts.mlp.v1", # dbrx
264
+ "model.layers.{bid}.mlp.experts.up_proj", # qwen2moe (merged)
265
+ ),
266
+ MODEL_TENSOR.FFN_UP_SHEXP: (
267
+ "model.layers.{bid}.mlp.shared_expert.up_proj", # qwen2moe
268
+ "model.layers.{bid}.mlp.shared_experts.up_proj", # deepseek2
269
+ ),
270
+ # AWQ-activation gate
271
+ MODEL_TENSOR.FFN_ACT: ("transformer.blocks.{bid}.ffn.act",), # mpt
272
+ # Feed-forward gate
273
+ MODEL_TENSOR.FFN_GATE: (
274
+ "model.layers.{bid}.mlp.gate_proj", # llama-hf refact
275
+ "layers.{bid}.feed_forward.w1", # llama-pth
276
+ "transformer.h.{bid}.mlp.w2", # qwen
277
+ "transformer.h.{bid}.mlp.c_fc2", # jais
278
+ "model.layers.layers.{bid}.mlp.gate_proj", # plamo
279
+ "model.layers.{bid}.feed_forward.w1", # internlm2
280
+ "encoder.layers.{bid}.mlp.fc12", # nomic-bert
281
+ "encoder.layer.{bid}.mlp.gated_layers_w", # jina-bert-v2
282
+ "transformer.h.{bid}.mlp.linear_1", # refact
283
+ "model.layers.{bid}.residual_mlp.w1", # arctic
284
+ ),
285
+ MODEL_TENSOR.FFN_GATE_EXP: (
286
+ "layers.{bid}.feed_forward.experts.w1", # mixtral (merged)
287
+ "transformer.decoder_layer.{bid}.moe.linear", # Grok (merged)
288
+ "transformer.blocks.{bid}.ffn.experts.mlp.w1", # dbrx
289
+ "model.layers.{bid}.mlp.experts.gate_proj", # qwen2moe (merged)
290
+ ),
291
+ MODEL_TENSOR.FFN_GATE_SHEXP: (
292
+ "model.layers.{bid}.mlp.shared_expert.gate_proj", # qwen2moe
293
+ "model.layers.{bid}.mlp.shared_experts.gate_proj", # deepseek2
294
+ ),
295
+ # Feed-forward down
296
+ MODEL_TENSOR.FFN_DOWN: (
297
+ "gpt_neox.layers.{bid}.mlp.dense_4h_to_h", # gptneox
298
+ "transformer.h.{bid}.mlp.c_proj", # gpt2 refact qwen jais
299
+ "transformer.blocks.{bid}.ffn.down_proj", # mpt
300
+ "transformer.h.{bid}.mlp.dense_4h_to_h", # falcon
301
+ "h.{bid}.mlp.dense_4h_to_h", # bloom
302
+ "model.layers.{bid}.mlp.down_proj", # llama-hf
303
+ "layers.{bid}.feed_forward.w2", # llama-pth
304
+ "encoder.layer.{bid}.output.dense", # bert
305
+ "transformer.h.{bid}.mlp.fc_out", # gpt-j
306
+ "language_model.encoder.layers.{bid}.mlp.dense_4h_to_h", # persimmon
307
+ "model.layers.{bid}.mlp.dense_4h_to_h", # persimmon
308
+ "h.{bid}.mlp.c_proj", # gpt2
309
+ "transformer.h.{bid}.mlp.fc2", # phi2
310
+ "model.layers.{bid}.mlp.fc2", # phi2
311
+ "model.layers.layers.{bid}.mlp.down_proj", # plamo
312
+ "model.layers.{bid}.feed_forward.w2", # internlm2
313
+ "encoder.layers.{bid}.mlp.fc2", # nomic-bert
314
+ "model.layers.{bid}.mlp.c_proj", # starcoder2
315
+ "encoder.layer.{bid}.mlp.wo", # jina-bert-v2
316
+ "transformer.layers.{bid}.ffn.proj_2", # openelm
317
+ "model.layers.{bid}.residual_mlp.w2", # arctic
318
+ "encoder.layer.{bid}.mlp.down_layer", # jina-bert-v2
319
+ "encoder.layers.{bid}.mlp.dense_4h_to_h", # chatglm
320
+ ),
321
+ MODEL_TENSOR.FFN_DOWN_EXP: (
322
+ "layers.{bid}.feed_forward.experts.w2", # mixtral (merged)
323
+ "transformer.decoder_layer.{bid}.moe.linear_1", # Grok (merged)
324
+ "transformer.blocks.{bid}.ffn.experts.mlp.w2", # dbrx
325
+ "model.layers.{bid}.mlp.experts.down_proj", # qwen2moe (merged)
326
+ ),
327
+ MODEL_TENSOR.FFN_DOWN_SHEXP: (
328
+ "model.layers.{bid}.mlp.shared_expert.down_proj", # qwen2moe
329
+ "model.layers.{bid}.mlp.shared_experts.down_proj", # deepseek2
330
+ ),
331
+ MODEL_TENSOR.ATTN_Q_NORM: (
332
+ "language_model.encoder.layers.{bid}.self_attention.q_layernorm",
333
+ "model.layers.{bid}.self_attn.q_layernorm", # persimmon
334
+ "model.layers.{bid}.self_attn.q_norm", # cohere
335
+ "transformer.blocks.{bid}.attn.q_ln", # sea-lion
336
+ "encoder.layer.{bid}.attention.self.layer_norm_q", # jina-bert-v2
337
+ "transformer.layers.{bid}.attn.q_norm", # openelm
338
+ ),
339
+ MODEL_TENSOR.ATTN_K_NORM: (
340
+ "language_model.encoder.layers.{bid}.self_attention.k_layernorm",
341
+ "model.layers.{bid}.self_attn.k_layernorm", # persimmon
342
+ "model.layers.{bid}.self_attn.k_norm", # cohere
343
+ "transformer.blocks.{bid}.attn.k_ln", # sea-lion
344
+ "encoder.layer.{bid}.attention.self.layer_norm_k", # jina-bert-v2
345
+ "transformer.layers.{bid}.attn.k_norm", # openelm
346
+ ),
347
+ MODEL_TENSOR.ROPE_FREQS: (
348
+ "language_model.encoder.layers.{bid}.self_attention.rotary_emb.inv_freq", # persimmon
349
+ ),
350
+ MODEL_TENSOR.LAYER_OUT_NORM: (
351
+ "encoder.layer.{bid}.output.LayerNorm", # bert
352
+ "encoder.layers.{bid}.norm2", # nomic-bert
353
+ "transformer.decoder_layer.{bid}.rms_norm_3", # Grok
354
+ "encoder.layer.{bid}.mlp.layernorm", # jina-bert-v2
355
+ "encoder.layer.{bid}.layer_norm_2", # jina-v2-code
356
+ ),
357
+ MODEL_TENSOR.SSM_IN: (
358
+ "model.layers.{bid}.in_proj",
359
+ "backbone.layers.{bid}.mixer.in_proj",
360
+ ),
361
+ MODEL_TENSOR.SSM_CONV1D: (
362
+ "model.layers.{bid}.conv1d",
363
+ "backbone.layers.{bid}.mixer.conv1d",
364
+ ),
365
+ MODEL_TENSOR.SSM_X: (
366
+ "model.layers.{bid}.x_proj",
367
+ "backbone.layers.{bid}.mixer.x_proj",
368
+ ),
369
+ MODEL_TENSOR.SSM_DT: (
370
+ "model.layers.{bid}.dt_proj",
371
+ "backbone.layers.{bid}.mixer.dt_proj",
372
+ ),
373
+ MODEL_TENSOR.SSM_A: (
374
+ "model.layers.{bid}.A_log",
375
+ "backbone.layers.{bid}.mixer.A_log",
376
+ ),
377
+ MODEL_TENSOR.SSM_D: (
378
+ "model.layers.{bid}.D",
379
+ "backbone.layers.{bid}.mixer.D",
380
+ ),
381
+ MODEL_TENSOR.SSM_OUT: (
382
+ "model.layers.{bid}.out_proj",
383
+ "backbone.layers.{bid}.mixer.out_proj",
384
+ ),
385
+ MODEL_TENSOR.ATTN_Q_A: ("model.layers.{bid}.self_attn.q_a_proj",), # deepseek2
386
+ MODEL_TENSOR.ATTN_Q_B: ("model.layers.{bid}.self_attn.q_b_proj",), # deepseek2
387
+ MODEL_TENSOR.ATTN_KV_A_MQA: (
388
+ "model.layers.{bid}.self_attn.kv_a_proj_with_mqa", # deepseek2
389
+ ),
390
+ MODEL_TENSOR.ATTN_KV_B: (
391
+ "model.layers.{bid}.self_attn.kv_b_proj", # deepseek2
392
+ ),
393
+ MODEL_TENSOR.ATTN_Q_A_NORM: (
394
+ "model.layers.{bid}.self_attn.q_a_layernorm", # deepseek2
395
+ ),
396
+ MODEL_TENSOR.ATTN_KV_A_NORM: (
397
+ "model.layers.{bid}.self_attn.kv_a_layernorm", # deepseek2
398
+ ),
399
+ MODEL_TENSOR.ATTN_SUB_NORM: (
400
+ "model.layers.{bid}.self_attn.inner_attn_ln", # bitnet
401
+ ),
402
+ MODEL_TENSOR.FFN_SUB_NORM: ("model.layers.{bid}.mlp.ffn_layernorm",), # bitnet
403
+ MODEL_TENSOR.DEC_ATTN_NORM: ("decoder.block.{bid}.layer.0.layer_norm",), # t5
404
+ MODEL_TENSOR.DEC_ATTN_Q: ("decoder.block.{bid}.layer.0.SelfAttention.q",), # t5
405
+ MODEL_TENSOR.DEC_ATTN_K: ("decoder.block.{bid}.layer.0.SelfAttention.k",), # t5
406
+ MODEL_TENSOR.DEC_ATTN_V: ("decoder.block.{bid}.layer.0.SelfAttention.v",), # t5
407
+ MODEL_TENSOR.DEC_ATTN_OUT: (
408
+ "decoder.block.{bid}.layer.0.SelfAttention.o", # t5
409
+ ),
410
+ MODEL_TENSOR.DEC_ATTN_REL_B: (
411
+ "decoder.block.{bid}.layer.0.SelfAttention.relative_attention_bias", # t5
412
+ ),
413
+ MODEL_TENSOR.DEC_CROSS_ATTN_NORM: (
414
+ "decoder.block.{bid}.layer.1.layer_norm", # t5
415
+ ),
416
+ MODEL_TENSOR.DEC_CROSS_ATTN_Q: (
417
+ "decoder.block.{bid}.layer.1.EncDecAttention.q", # t5
418
+ ),
419
+ MODEL_TENSOR.DEC_CROSS_ATTN_K: (
420
+ "decoder.block.{bid}.layer.1.EncDecAttention.k", # t5
421
+ ),
422
+ MODEL_TENSOR.DEC_CROSS_ATTN_V: (
423
+ "decoder.block.{bid}.layer.1.EncDecAttention.v", # t5
424
+ ),
425
+ MODEL_TENSOR.DEC_CROSS_ATTN_OUT: (
426
+ "decoder.block.{bid}.layer.1.EncDecAttention.o", # t5
427
+ ),
428
+ MODEL_TENSOR.DEC_CROSS_ATTN_REL_B: (
429
+ "decoder.block.{bid}.layer.1.EncDecAttention.relative_attention_bias", # t5
430
+ ),
431
+ MODEL_TENSOR.DEC_FFN_NORM: ("decoder.block.{bid}.layer.2.layer_norm",), # t5
432
+ MODEL_TENSOR.DEC_FFN_GATE: (
433
+ "decoder.block.{bid}.layer.2.DenseReluDense.wi_0", # flan-t5
434
+ ),
435
+ MODEL_TENSOR.DEC_FFN_UP: (
436
+ "decoder.block.{bid}.layer.2.DenseReluDense.wi", # t5
437
+ "decoder.block.{bid}.layer.2.DenseReluDense.wi_1", # flan-t5
438
+ ),
439
+ MODEL_TENSOR.DEC_FFN_DOWN: (
440
+ "decoder.block.{bid}.layer.2.DenseReluDense.wo", # t5
441
+ ),
442
+ MODEL_TENSOR.DEC_OUTPUT_NORM: ("decoder.final_layer_norm",), # t5
443
+ MODEL_TENSOR.ENC_ATTN_NORM: ("encoder.block.{bid}.layer.0.layer_norm",), # t5
444
+ MODEL_TENSOR.ENC_ATTN_Q: ("encoder.block.{bid}.layer.0.SelfAttention.q",), # t5
445
+ MODEL_TENSOR.ENC_ATTN_K: ("encoder.block.{bid}.layer.0.SelfAttention.k",), # t5
446
+ MODEL_TENSOR.ENC_ATTN_V: ("encoder.block.{bid}.layer.0.SelfAttention.v",), # t5
447
+ MODEL_TENSOR.ENC_ATTN_OUT: (
448
+ "encoder.block.{bid}.layer.0.SelfAttention.o", # t5
449
+ ),
450
+ MODEL_TENSOR.ENC_ATTN_REL_B: (
451
+ "encoder.block.{bid}.layer.0.SelfAttention.relative_attention_bias", # t5
452
+ ),
453
+ MODEL_TENSOR.ENC_FFN_NORM: ("encoder.block.{bid}.layer.1.layer_norm",), # t5
454
+ MODEL_TENSOR.ENC_FFN_GATE: (
455
+ "encoder.block.{bid}.layer.1.DenseReluDense.wi_0", # flan-t5
456
+ ),
457
+ MODEL_TENSOR.ENC_FFN_UP: (
458
+ "encoder.block.{bid}.layer.1.DenseReluDense.wi", # t5
459
+ "encoder.block.{bid}.layer.1.DenseReluDense.wi_1", # flan-t5
460
+ ),
461
+ MODEL_TENSOR.ENC_FFN_DOWN: (
462
+ "encoder.block.{bid}.layer.1.DenseReluDense.wo", # t5
463
+ ),
464
+ MODEL_TENSOR.ENC_OUTPUT_NORM: ("encoder.final_layer_norm",), # t5
465
+ }
466
+
467
+ # architecture-specific block mappings
468
+ arch_block_mappings_cfg: dict[MODEL_ARCH, dict[MODEL_TENSOR, tuple[str, ...]]] = {
469
+ MODEL_ARCH.ARCTIC: {
470
+ MODEL_TENSOR.FFN_NORM: ("model.layers.{bid}.residual_layernorm",),
471
+ MODEL_TENSOR.FFN_NORM_EXP: ("model.layers.{bid}.post_attention_layernorm",),
472
+ },
473
+ }
474
+
475
+ mapping: dict[str, tuple[MODEL_TENSOR, str]]
476
+
477
+ def __init__(self, arch: MODEL_ARCH, n_blocks: int):
478
+ self.mapping = {}
479
+ for tensor, keys in self.mappings_cfg.items():
480
+ if tensor not in MODEL_TENSORS[arch]:
481
+ continue
482
+ tensor_name = TENSOR_NAMES[tensor]
483
+ self.mapping[tensor_name] = (tensor, tensor_name)
484
+ for key in keys:
485
+ self.mapping[key] = (tensor, tensor_name)
486
+ if arch in self.arch_block_mappings_cfg:
487
+ self.block_mappings_cfg.update(self.arch_block_mappings_cfg[arch])
488
+ for bid in range(n_blocks):
489
+ for tensor, keys in self.block_mappings_cfg.items():
490
+ if tensor not in MODEL_TENSORS[arch]:
491
+ continue
492
+
493
+ tensor_name = TENSOR_NAMES[tensor].format(bid=bid)
494
+ self.mapping[tensor_name] = (tensor, tensor_name)
495
+ for key in keys:
496
+ key = key.format(bid=bid)
497
+ self.mapping[key] = (tensor, tensor_name)
498
+
499
+ def get_type_and_name(
500
+ self, key: str, try_suffixes: Sequence[str] = ()
501
+ ) -> tuple[MODEL_TENSOR, str] | None:
502
+ result = self.mapping.get(key)
503
+ if result is not None:
504
+ return result
505
+ for suffix in try_suffixes:
506
+ if key.endswith(suffix):
507
+ result = self.mapping.get(key[: -len(suffix)])
508
+ if result is not None:
509
+ return result[0], result[1] + suffix
510
+ return None
511
+
512
+ def get_name(self, key: str, try_suffixes: Sequence[str] = ()) -> str | None:
513
+ result = self.get_type_and_name(key, try_suffixes=try_suffixes)
514
+ if result is None:
515
+ return None
516
+ return result[1]
517
+
518
+ def get_type(
519
+ self, key: str, try_suffixes: Sequence[str] = ()
520
+ ) -> MODEL_TENSOR | None:
521
+ result = self.get_type_and_name(key, try_suffixes=try_suffixes)
522
+ if result is None:
523
+ return None
524
+ return result[0]
525
+
526
+ def __getitem__(self, key: str) -> str:
527
+ try:
528
+ return self.mapping[key][1]
529
+ except KeyError:
530
+ raise KeyError(key)
531
+
532
+ def __contains__(self, key: str) -> bool:
533
+ return key in self.mapping
534
+
535
+ def __repr__(self) -> str:
536
+ return repr(self.mapping)
537
+
538
+
539
+ def get_tensor_name_map(arch: MODEL_ARCH, n_blocks: int) -> TensorNameMap:
540
+ return TensorNameMap(arch, n_blocks)
modules_forge/packages/gguf/utility.py ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from typing import Literal
4
+
5
+
6
+ def fill_templated_filename(filename: str, output_type: str | None) -> str:
7
+ # Given a file name fill in any type templates e.g. 'some-model-name.{ftype}.gguf'
8
+ ftype_lowercase: str = output_type.lower() if output_type is not None else ""
9
+ ftype_uppercase: str = output_type.upper() if output_type is not None else ""
10
+ return filename.format(
11
+ ftype_lowercase,
12
+ outtype=ftype_lowercase,
13
+ ftype=ftype_lowercase,
14
+ OUTTYPE=ftype_uppercase,
15
+ FTYPE=ftype_uppercase,
16
+ )
17
+
18
+
19
+ def model_weight_count_rounded_notation(
20
+ model_params_count: int, min_digits: int = 2
21
+ ) -> str:
22
+ if model_params_count > 1e12:
23
+ # Trillions Of Parameters
24
+ scaled_model_params = model_params_count * 1e-12
25
+ scale_suffix = "T"
26
+ elif model_params_count > 1e9:
27
+ # Billions Of Parameters
28
+ scaled_model_params = model_params_count * 1e-9
29
+ scale_suffix = "B"
30
+ elif model_params_count > 1e6:
31
+ # Millions Of Parameters
32
+ scaled_model_params = model_params_count * 1e-6
33
+ scale_suffix = "M"
34
+ else:
35
+ # Thousands Of Parameters
36
+ scaled_model_params = model_params_count * 1e-3
37
+ scale_suffix = "K"
38
+
39
+ fix = max(min_digits - len(str(round(scaled_model_params)).lstrip("0")), 0)
40
+
41
+ return f"{scaled_model_params:.{fix}f}{scale_suffix}"
42
+
43
+
44
+ def size_label(
45
+ total_params: int, shared_params: int, expert_params: int, expert_count: int
46
+ ) -> str:
47
+
48
+ if expert_count > 0:
49
+ pretty_size = model_weight_count_rounded_notation(
50
+ abs(shared_params) + abs(expert_params), min_digits=2
51
+ )
52
+ size_class = f"{expert_count}x{pretty_size}"
53
+ else:
54
+ size_class = model_weight_count_rounded_notation(
55
+ abs(total_params), min_digits=2
56
+ )
57
+
58
+ return size_class
59
+
60
+
61
+ def naming_convention(
62
+ model_name: str | None,
63
+ base_name: str | None,
64
+ finetune_string: str | None,
65
+ version_string: str | None,
66
+ size_label: str | None,
67
+ output_type: str | None,
68
+ model_type: Literal["vocab", "LoRA"] | None = None,
69
+ ) -> str:
70
+ # Reference: https://github.com/ggerganov/ggml/blob/master/docs/gguf.md#gguf-naming-convention
71
+
72
+ if base_name is not None:
73
+ name = base_name.strip().replace(" ", "-").replace("/", "-")
74
+ elif model_name is not None:
75
+ name = model_name.strip().replace(" ", "-").replace("/", "-")
76
+ else:
77
+ name = "ggml-model"
78
+
79
+ parameters = f"-{size_label}" if size_label is not None else ""
80
+
81
+ finetune = (
82
+ f"-{finetune_string.strip().replace(' ', '-')}"
83
+ if finetune_string is not None
84
+ else ""
85
+ )
86
+
87
+ version = (
88
+ f"-{version_string.strip().replace(' ', '-')}"
89
+ if version_string is not None
90
+ else ""
91
+ )
92
+
93
+ encoding = (
94
+ f"-{output_type.strip().replace(' ', '-').upper()}"
95
+ if output_type is not None
96
+ else ""
97
+ )
98
+
99
+ kind = f"-{model_type.strip().replace(' ', '-')}" if model_type is not None else ""
100
+
101
+ return f"{name}{parameters}{finetune}{version}{encoding}{kind}"
modules_forge/packages/huggingface_guess/LICENSE ADDED
@@ -0,0 +1,621 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ GNU GENERAL PUBLIC LICENSE
2
+ Version 3, 29 June 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 General Public License is a free, copyleft license for
11
+ software and other kinds of works.
12
+
13
+ The licenses for most software and other practical works are designed
14
+ to take away your freedom to share and change the works. By contrast,
15
+ the GNU General Public License is intended to guarantee your freedom to
16
+ share and change all versions of a program--to make sure it remains free
17
+ software for all its users. We, the Free Software Foundation, use the
18
+ GNU General Public License for most of our software; it applies also to
19
+ any other work released this way by its authors. You can apply it to
20
+ your programs, too.
21
+
22
+ When we speak of free software, we are referring to freedom, not
23
+ price. Our General Public Licenses are designed to make sure that you
24
+ have the freedom to distribute copies of free software (and charge for
25
+ them if you wish), that you receive source code or can get it if you
26
+ want it, that you can change the software or use pieces of it in new
27
+ free programs, and that you know you can do these things.
28
+
29
+ To protect your rights, we need to prevent others from denying you
30
+ these rights or asking you to surrender the rights. Therefore, you have
31
+ certain responsibilities if you distribute copies of the software, or if
32
+ you modify it: responsibilities to respect the freedom of others.
33
+
34
+ For example, if you distribute copies of such a program, whether
35
+ gratis or for a fee, you must pass on to the recipients the same
36
+ freedoms that you received. You must make sure that they, too, receive
37
+ or can get the source code. And you must show them these terms so they
38
+ know their rights.
39
+
40
+ Developers that use the GNU GPL protect your rights with two steps:
41
+ (1) assert copyright on the software, and (2) offer you this License
42
+ giving you legal permission to copy, distribute and/or modify it.
43
+
44
+ For the developers' and authors' protection, the GPL clearly explains
45
+ that there is no warranty for this free software. For both users' and
46
+ authors' sake, the GPL requires that modified versions be marked as
47
+ changed, so that their problems will not be attributed erroneously to
48
+ authors of previous versions.
49
+
50
+ Some devices are designed to deny users access to install or run
51
+ modified versions of the software inside them, although the manufacturer
52
+ can do so. This is fundamentally incompatible with the aim of
53
+ protecting users' freedom to change the software. The systematic
54
+ pattern of such abuse occurs in the area of products for individuals to
55
+ use, which is precisely where it is most unacceptable. Therefore, we
56
+ have designed this version of the GPL to prohibit the practice for those
57
+ products. If such problems arise substantially in other domains, we
58
+ stand ready to extend this provision to those domains in future versions
59
+ of the GPL, as needed to protect the freedom of users.
60
+
61
+ Finally, every program is threatened constantly by software patents.
62
+ States should not allow patents to restrict development and use of
63
+ software on general-purpose computers, but in those that do, we wish to
64
+ avoid the special danger that patents applied to a free program could
65
+ make it effectively proprietary. To prevent this, the GPL assures that
66
+ patents cannot be used to render the program non-free.
67
+
68
+ The precise terms and conditions for copying, distribution and
69
+ modification follow.
70
+
71
+ TERMS AND CONDITIONS
72
+
73
+ 0. Definitions.
74
+
75
+ "This License" refers to version 3 of the GNU General Public License.
76
+
77
+ "Copyright" also means copyright-like laws that apply to other kinds of
78
+ works, such as semiconductor masks.
79
+
80
+ "The Program" refers to any copyrightable work licensed under this
81
+ License. Each licensee is addressed as "you". "Licensees" and
82
+ "recipients" may be individuals or organizations.
83
+
84
+ To "modify" a work means to copy from or adapt all or part of the work
85
+ in a fashion requiring copyright permission, other than the making of an
86
+ exact copy. The resulting work is called a "modified version" of the
87
+ earlier work or a work "based on" the earlier work.
88
+
89
+ A "covered work" means either the unmodified Program or a work based
90
+ on the Program.
91
+
92
+ To "propagate" a work means to do anything with it that, without
93
+ permission, would make you directly or secondarily liable for
94
+ infringement under applicable copyright law, except executing it on a
95
+ computer or modifying a private copy. Propagation includes copying,
96
+ distribution (with or without modification), making available to the
97
+ public, and in some countries other activities as well.
98
+
99
+ To "convey" a work means any kind of propagation that enables other
100
+ parties to make or receive copies. Mere interaction with a user through
101
+ a computer network, with no transfer of a copy, is not conveying.
102
+
103
+ An interactive user interface displays "Appropriate Legal Notices"
104
+ to the extent that it includes a convenient and prominently visible
105
+ feature that (1) displays an appropriate copyright notice, and (2)
106
+ tells the user that there is no warranty for the work (except to the
107
+ extent that warranties are provided), that licensees may convey the
108
+ work under this License, and how to view a copy of this License. If
109
+ the interface presents a list of user commands or options, such as a
110
+ menu, a prominent item in the list meets this criterion.
111
+
112
+ 1. Source Code.
113
+
114
+ The "source code" for a work means the preferred form of the work
115
+ for making modifications to it. "Object code" means any non-source
116
+ form of a work.
117
+
118
+ A "Standard Interface" means an interface that either is an official
119
+ standard defined by a recognized standards body, or, in the case of
120
+ interfaces specified for a particular programming language, one that
121
+ is widely used among developers working in that language.
122
+
123
+ The "System Libraries" of an executable work include anything, other
124
+ than the work as a whole, that (a) is included in the normal form of
125
+ packaging a Major Component, but which is not part of that Major
126
+ Component, and (b) serves only to enable use of the work with that
127
+ Major Component, or to implement a Standard Interface for which an
128
+ implementation is available to the public in source code form. A
129
+ "Major Component", in this context, means a major essential component
130
+ (kernel, window system, and so on) of the specific operating system
131
+ (if any) on which the executable work runs, or a compiler used to
132
+ produce the work, or an object code interpreter used to run it.
133
+
134
+ The "Corresponding Source" for a work in object code form means all
135
+ the source code needed to generate, install, and (for an executable
136
+ work) run the object code and to modify the work, including scripts to
137
+ control those activities. However, it does not include the work's
138
+ System Libraries, or general-purpose tools or generally available free
139
+ programs which are used unmodified in performing those activities but
140
+ which are not part of the work. For example, Corresponding Source
141
+ includes interface definition files associated with source files for
142
+ the work, and the source code for shared libraries and dynamically
143
+ linked subprograms that the work is specifically designed to require,
144
+ such as by intimate data communication or control flow between those
145
+ subprograms and other parts of the work.
146
+
147
+ The Corresponding Source need not include anything that users
148
+ can regenerate automatically from other parts of the Corresponding
149
+ Source.
150
+
151
+ The Corresponding Source for a work in source code form is that
152
+ same work.
153
+
154
+ 2. Basic Permissions.
155
+
156
+ All rights granted under this License are granted for the term of
157
+ copyright on the Program, and are irrevocable provided the stated
158
+ conditions are met. This License explicitly affirms your unlimited
159
+ permission to run the unmodified Program. The output from running a
160
+ covered work is covered by this License only if the output, given its
161
+ content, constitutes a covered work. This License acknowledges your
162
+ rights of fair use or other equivalent, as provided by copyright law.
163
+
164
+ You may make, run and propagate covered works that you do not
165
+ convey, without conditions so long as your license otherwise remains
166
+ in force. You may convey covered works to others for the sole purpose
167
+ of having them make modifications exclusively for you, or provide you
168
+ with facilities for running those works, provided that you comply with
169
+ the terms of this License in conveying all material for which you do
170
+ not control copyright. Those thus making or running the covered works
171
+ for you must do so exclusively on your behalf, under your direction
172
+ and control, on terms that prohibit them from making any copies of
173
+ your copyrighted material outside their relationship with you.
174
+
175
+ Conveying under any other circumstances is permitted solely under
176
+ the conditions stated below. Sublicensing is not allowed; section 10
177
+ makes it unnecessary.
178
+
179
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180
+
181
+ No covered work shall be deemed part of an effective technological
182
+ measure under any applicable law fulfilling obligations under article
183
+ 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184
+ similar laws prohibiting or restricting circumvention of such
185
+ measures.
186
+
187
+ When you convey a covered work, you waive any legal power to forbid
188
+ circumvention of technological measures to the extent such circumvention
189
+ is effected by exercising rights under this License with respect to
190
+ the covered work, and you disclaim any intention to limit operation or
191
+ modification of the work as a means of enforcing, against the work's
192
+ users, your or third parties' legal rights to forbid circumvention of
193
+ technological measures.
194
+
195
+ 4. Conveying Verbatim Copies.
196
+
197
+ You may convey verbatim copies of the Program's source code as you
198
+ receive it, in any medium, provided that you conspicuously and
199
+ appropriately publish on each copy an appropriate copyright notice;
200
+ keep intact all notices stating that this License and any
201
+ non-permissive terms added in accord with section 7 apply to the code;
202
+ keep intact all notices of the absence of any warranty; and give all
203
+ recipients a copy of this License along with the Program.
204
+
205
+ You may charge any price or no price for each copy that you convey,
206
+ and you may offer support or warranty protection for a fee.
207
+
208
+ 5. Conveying Modified Source Versions.
209
+
210
+ You may convey a work based on the Program, or the modifications to
211
+ produce it from the Program, in the form of source code under the
212
+ terms of section 4, provided that you also meet all of these conditions:
213
+
214
+ a) The work must carry prominent notices stating that you modified
215
+ it, and giving a relevant date.
216
+
217
+ b) The work must carry prominent notices stating that it is
218
+ released under this License and any conditions added under section
219
+ 7. This requirement modifies the requirement in section 4 to
220
+ "keep intact all notices".
221
+
222
+ c) You must license the entire work, as a whole, under this
223
+ License to anyone who comes into possession of a copy. This
224
+ License will therefore apply, along with any applicable section 7
225
+ additional terms, to the whole of the work, and all its parts,
226
+ regardless of how they are packaged. This License gives no
227
+ permission to license the work in any other way, but it does not
228
+ invalidate such permission if you have separately received it.
229
+
230
+ d) If the work has interactive user interfaces, each must display
231
+ Appropriate Legal Notices; however, if the Program has interactive
232
+ interfaces that do not display Appropriate Legal Notices, your
233
+ work need not make them do so.
234
+
235
+ A compilation of a covered work with other separate and independent
236
+ works, which are not by their nature extensions of the covered work,
237
+ and which are not combined with it such as to form a larger program,
238
+ in or on a volume of a storage or distribution medium, is called an
239
+ "aggregate" if the compilation and its resulting copyright are not
240
+ used to limit the access or legal rights of the compilation's users
241
+ beyond what the individual works permit. Inclusion of a covered work
242
+ in an aggregate does not cause this License to apply to the other
243
+ parts of the aggregate.
244
+
245
+ 6. Conveying Non-Source Forms.
246
+
247
+ You may convey a covered work in object code form under the terms
248
+ of sections 4 and 5, provided that you also convey the
249
+ machine-readable Corresponding Source under the terms of this License,
250
+ in one of these ways:
251
+
252
+ a) Convey the object code in, or embodied in, a physical product
253
+ (including a physical distribution medium), accompanied by the
254
+ Corresponding Source fixed on a durable physical medium
255
+ customarily used for software interchange.
256
+
257
+ b) Convey the object code in, or embodied in, a physical product
258
+ (including a physical distribution medium), accompanied by a
259
+ written offer, valid for at least three years and valid for as
260
+ long as you offer spare parts or customer support for that product
261
+ model, to give anyone who possesses the object code either (1) a
262
+ copy of the Corresponding Source for all the software in the
263
+ product that is covered by this License, on a durable physical
264
+ medium customarily used for software interchange, for a price no
265
+ more than your reasonable cost of physically performing this
266
+ conveying of source, or (2) access to copy the
267
+ Corresponding Source from a network server at no charge.
268
+
269
+ c) Convey individual copies of the object code with a copy of the
270
+ written offer to provide the Corresponding Source. This
271
+ alternative is allowed only occasionally and noncommercially, and
272
+ only if you received the object code with such an offer, in accord
273
+ with subsection 6b.
274
+
275
+ d) Convey the object code by offering access from a designated
276
+ place (gratis or for a charge), and offer equivalent access to the
277
+ Corresponding Source in the same way through the same place at no
278
+ further charge. You need not require recipients to copy the
279
+ Corresponding Source along with the object code. If the place to
280
+ copy the object code is a network server, the Corresponding Source
281
+ may be on a different server (operated by you or a third party)
282
+ that supports equivalent copying facilities, provided you maintain
283
+ clear directions next to the object code saying where to find the
284
+ Corresponding Source. Regardless of what server hosts the
285
+ Corresponding Source, you remain obligated to ensure that it is
286
+ available for as long as needed to satisfy these requirements.
287
+
288
+ e) Convey the object code using peer-to-peer transmission, provided
289
+ you inform other peers where the object code and Corresponding
290
+ Source of the work are being offered to the general public at no
291
+ charge under subsection 6d.
292
+
293
+ A separable portion of the object code, whose source code is excluded
294
+ from the Corresponding Source as a System Library, need not be
295
+ included in conveying the object code work.
296
+
297
+ A "User Product" is either (1) a "consumer product", which means any
298
+ tangible personal property which is normally used for personal, family,
299
+ or household purposes, or (2) anything designed or sold for incorporation
300
+ into a dwelling. In determining whether a product is a consumer product,
301
+ doubtful cases shall be resolved in favor of coverage. For a particular
302
+ product received by a particular user, "normally used" refers to a
303
+ typical or common use of that class of product, regardless of the status
304
+ of the particular user or of the way in which the particular user
305
+ actually uses, or expects or is expected to use, the product. A product
306
+ is a consumer product regardless of whether the product has substantial
307
+ commercial, industrial or non-consumer uses, unless such uses represent
308
+ the only significant mode of use of the product.
309
+
310
+ "Installation Information" for a User Product means any methods,
311
+ procedures, authorization keys, or other information required to install
312
+ and execute modified versions of a covered work in that User Product from
313
+ a modified version of its Corresponding Source. The information must
314
+ suffice to ensure that the continued functioning of the modified object
315
+ code is in no case prevented or interfered with solely because
316
+ modification has been made.
317
+
318
+ If you convey an object code work under this section in, or with, or
319
+ specifically for use in, a User Product, and the conveying occurs as
320
+ part of a transaction in which the right of possession and use of the
321
+ User Product is transferred to the recipient in perpetuity or for a
322
+ fixed term (regardless of how the transaction is characterized), the
323
+ Corresponding Source conveyed under this section must be accompanied
324
+ by the Installation Information. But this requirement does not apply
325
+ if neither you nor any third party retains the ability to install
326
+ modified object code on the User Product (for example, the work has
327
+ been installed in ROM).
328
+
329
+ The requirement to provide Installation Information does not include a
330
+ requirement to continue to provide support service, warranty, or updates
331
+ for a work that has been modified or installed by the recipient, or for
332
+ the User Product in which it has been modified or installed. Access to a
333
+ network may be denied when the modification itself materially and
334
+ adversely affects the operation of the network or violates the rules and
335
+ protocols for communication across the network.
336
+
337
+ Corresponding Source conveyed, and Installation Information provided,
338
+ in accord with this section must be in a format that is publicly
339
+ documented (and with an implementation available to the public in
340
+ source code form), and must require no special password or key for
341
+ unpacking, reading or copying.
342
+
343
+ 7. Additional Terms.
344
+
345
+ "Additional permissions" are terms that supplement the terms of this
346
+ License by making exceptions from one or more of its conditions.
347
+ Additional permissions that are applicable to the entire Program shall
348
+ be treated as though they were included in this License, to the extent
349
+ that they are valid under applicable law. If additional permissions
350
+ apply only to part of the Program, that part may be used separately
351
+ under those permissions, but the entire Program remains governed by
352
+ this License without regard to the additional permissions.
353
+
354
+ When you convey a copy of a covered work, you may at your option
355
+ remove any additional permissions from that copy, or from any part of
356
+ it. (Additional permissions may be written to require their own
357
+ removal in certain cases when you modify the work.) You may place
358
+ additional permissions on material, added by you to a covered work,
359
+ for which you have or can give appropriate copyright permission.
360
+
361
+ Notwithstanding any other provision of this License, for material you
362
+ add to a covered work, you may (if authorized by the copyright holders of
363
+ that material) supplement the terms of this License with terms:
364
+
365
+ a) Disclaiming warranty or limiting liability differently from the
366
+ terms of sections 15 and 16 of this License; or
367
+
368
+ b) Requiring preservation of specified reasonable legal notices or
369
+ author attributions in that material or in the Appropriate Legal
370
+ Notices displayed by works containing it; or
371
+
372
+ c) Prohibiting misrepresentation of the origin of that material, or
373
+ requiring that modified versions of such material be marked in
374
+ reasonable ways as different from the original version; or
375
+
376
+ d) Limiting the use for publicity purposes of names of licensors or
377
+ authors of the material; or
378
+
379
+ e) Declining to grant rights under trademark law for use of some
380
+ trade names, trademarks, or service marks; or
381
+
382
+ f) Requiring indemnification of licensors and authors of that
383
+ material by anyone who conveys the material (or modified versions of
384
+ it) with contractual assumptions of liability to the recipient, for
385
+ any liability that these contractual assumptions directly impose on
386
+ those licensors and authors.
387
+
388
+ All other non-permissive additional terms are considered "further
389
+ restrictions" within the meaning of section 10. If the Program as you
390
+ received it, or any part of it, contains a notice stating that it is
391
+ governed by this License along with a term that is a further
392
+ restriction, you may remove that term. If a license document contains
393
+ a further restriction but permits relicensing or conveying under this
394
+ License, you may add to a covered work material governed by the terms
395
+ of that license document, provided that the further restriction does
396
+ not survive such relicensing or conveying.
397
+
398
+ If you add terms to a covered work in accord with this section, you
399
+ must place, in the relevant source files, a statement of the
400
+ additional terms that apply to those files, or a notice indicating
401
+ where to find the applicable terms.
402
+
403
+ Additional terms, permissive or non-permissive, may be stated in the
404
+ form of a separately written license, or stated as exceptions;
405
+ the above requirements apply either way.
406
+
407
+ 8. Termination.
408
+
409
+ You may not propagate or modify a covered work except as expressly
410
+ provided under this License. Any attempt otherwise to propagate or
411
+ modify it is void, and will automatically terminate your rights under
412
+ this License (including any patent licenses granted under the third
413
+ paragraph of section 11).
414
+
415
+ However, if you cease all violation of this License, then your
416
+ license from a particular copyright holder is reinstated (a)
417
+ provisionally, unless and until the copyright holder explicitly and
418
+ finally terminates your license, and (b) permanently, if the copyright
419
+ holder fails to notify you of the violation by some reasonable means
420
+ prior to 60 days after the cessation.
421
+
422
+ Moreover, your license from a particular copyright holder is
423
+ reinstated permanently if the copyright holder notifies you of the
424
+ violation by some reasonable means, this is the first time you have
425
+ received notice of violation of this License (for any work) from that
426
+ copyright holder, and you cure the violation prior to 30 days after
427
+ your receipt of the notice.
428
+
429
+ Termination of your rights under this section does not terminate the
430
+ licenses of parties who have received copies or rights from you under
431
+ this License. If your rights have been terminated and not permanently
432
+ reinstated, you do not qualify to receive new licenses for the same
433
+ material under section 10.
434
+
435
+ 9. Acceptance Not Required for Having Copies.
436
+
437
+ You are not required to accept this License in order to receive or
438
+ run a copy of the Program. Ancillary propagation of a covered work
439
+ occurring solely as a consequence of using peer-to-peer transmission
440
+ to receive a copy likewise does not require acceptance. However,
441
+ nothing other than this License grants you permission to propagate or
442
+ modify any covered work. These actions infringe copyright if you do
443
+ not accept this License. Therefore, by modifying or propagating a
444
+ covered work, you indicate your acceptance of this License to do so.
445
+
446
+ 10. Automatic Licensing of Downstream Recipients.
447
+
448
+ Each time you convey a covered work, the recipient automatically
449
+ receives a license from the original licensors, to run, modify and
450
+ propagate that work, subject to this License. You are not responsible
451
+ for enforcing compliance by third parties with this License.
452
+
453
+ An "entity transaction" is a transaction transferring control of an
454
+ organization, or substantially all assets of one, or subdividing an
455
+ organization, or merging organizations. If propagation of a covered
456
+ work results from an entity transaction, each party to that
457
+ transaction who receives a copy of the work also receives whatever
458
+ licenses to the work the party's predecessor in interest had or could
459
+ give under the previous paragraph, plus a right to possession of the
460
+ Corresponding Source of the work from the predecessor in interest, if
461
+ the predecessor has it or can get it with reasonable efforts.
462
+
463
+ You may not impose any further restrictions on the exercise of the
464
+ rights granted or affirmed under this License. For example, you may
465
+ not impose a license fee, royalty, or other charge for exercise of
466
+ rights granted under this License, and you may not initiate litigation
467
+ (including a cross-claim or counterclaim in a lawsuit) alleging that
468
+ any patent claim is infringed by making, using, selling, offering for
469
+ sale, or importing the Program or any portion of it.
470
+
471
+ 11. Patents.
472
+
473
+ A "contributor" is a copyright holder who authorizes use under this
474
+ License of the Program or a work on which the Program is based. The
475
+ work thus licensed is called the contributor's "contributor version".
476
+
477
+ A contributor's "essential patent claims" are all patent claims
478
+ owned or controlled by the contributor, whether already acquired or
479
+ hereafter acquired, that would be infringed by some manner, permitted
480
+ by this License, of making, using, or selling its contributor version,
481
+ but do not include claims that would be infringed only as a
482
+ consequence of further modification of the contributor version. For
483
+ purposes of this definition, "control" includes the right to grant
484
+ patent sublicenses in a manner consistent with the requirements of
485
+ this License.
486
+
487
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
488
+ patent license under the contributor's essential patent claims, to
489
+ make, use, sell, offer for sale, import and otherwise run, modify and
490
+ propagate the contents of its contributor version.
491
+
492
+ In the following three paragraphs, a "patent license" is any express
493
+ agreement or commitment, however denominated, not to enforce a patent
494
+ (such as an express permission to practice a patent or covenant not to
495
+ sue for patent infringement). To "grant" such a patent license to a
496
+ party means to make such an agreement or commitment not to enforce a
497
+ patent against the party.
498
+
499
+ If you convey a covered work, knowingly relying on a patent license,
500
+ and the Corresponding Source of the work is not available for anyone
501
+ to copy, free of charge and under the terms of this License, through a
502
+ publicly available network server or other readily accessible means,
503
+ then you must either (1) cause the Corresponding Source to be so
504
+ available, or (2) arrange to deprive yourself of the benefit of the
505
+ patent license for this particular work, or (3) arrange, in a manner
506
+ consistent with the requirements of this License, to extend the patent
507
+ license to downstream recipients. "Knowingly relying" means you have
508
+ actual knowledge that, but for the patent license, your conveying the
509
+ covered work in a country, or your recipient's use of the covered work
510
+ in a country, would infringe one or more identifiable patents in that
511
+ country that you have reason to believe are valid.
512
+
513
+ If, pursuant to or in connection with a single transaction or
514
+ arrangement, you convey, or propagate by procuring conveyance of, a
515
+ covered work, and grant a patent license to some of the parties
516
+ receiving the covered work authorizing them to use, propagate, modify
517
+ or convey a specific copy of the covered work, then the patent license
518
+ you grant is automatically extended to all recipients of the covered
519
+ work and works based on it.
520
+
521
+ A patent license is "discriminatory" if it does not include within
522
+ the scope of its coverage, prohibits the exercise of, or is
523
+ conditioned on the non-exercise of one or more of the rights that are
524
+ specifically granted under this License. You may not convey a covered
525
+ work if you are a party to an arrangement with a third party that is
526
+ in the business of distributing software, under which you make payment
527
+ to the third party based on the extent of your activity of conveying
528
+ the work, and under which the third party grants, to any of the
529
+ parties who would receive the covered work from you, a discriminatory
530
+ patent license (a) in connection with copies of the covered work
531
+ conveyed by you (or copies made from those copies), or (b) primarily
532
+ for and in connection with specific products or compilations that
533
+ contain the covered work, unless you entered into that arrangement,
534
+ or that patent license was granted, prior to 28 March 2007.
535
+
536
+ Nothing in this License shall be construed as excluding or limiting
537
+ any implied license or other defenses to infringement that may
538
+ otherwise be available to you under applicable patent law.
539
+
540
+ 12. No Surrender of Others' Freedom.
541
+
542
+ If conditions are imposed on you (whether by court order, agreement or
543
+ otherwise) that contradict the conditions of this License, they do not
544
+ excuse you from the conditions of this License. If you cannot convey a
545
+ covered work so as to satisfy simultaneously your obligations under this
546
+ License and any other pertinent obligations, then as a consequence you may
547
+ not convey it at all. For example, if you agree to terms that obligate you
548
+ to collect a royalty for further conveying from those to whom you convey
549
+ the Program, the only way you could satisfy both those terms and this
550
+ License would be to refrain entirely from conveying the Program.
551
+
552
+ 13. Use with the GNU Affero General Public License.
553
+
554
+ Notwithstanding any other provision of this License, you have
555
+ permission to link or combine any covered work with a work licensed
556
+ under version 3 of the GNU Affero General Public License into a single
557
+ combined work, and to convey the resulting work. The terms of this
558
+ License will continue to apply to the part which is the covered work,
559
+ but the special requirements of the GNU Affero General Public License,
560
+ section 13, concerning interaction through a network will apply to the
561
+ combination as such.
562
+
563
+ 14. Revised Versions of this License.
564
+
565
+ The Free Software Foundation may publish revised and/or new versions of
566
+ the GNU General Public License from time to time. Such new versions will
567
+ be similar in spirit to the present version, but may differ in detail to
568
+ address new problems or concerns.
569
+
570
+ Each version is given a distinguishing version number. If the
571
+ Program specifies that a certain numbered version of the GNU General
572
+ Public License "or any later version" applies to it, you have the
573
+ option of following the terms and conditions either of that numbered
574
+ version or of any later version published by the Free Software
575
+ Foundation. If the Program does not specify a version number of the
576
+ GNU General Public License, you may choose any version ever published
577
+ by the Free Software Foundation.
578
+
579
+ If the Program specifies that a proxy can decide which future
580
+ versions of the GNU General Public License can be used, that proxy's
581
+ public statement of acceptance of a version permanently authorizes you
582
+ to choose that version for the Program.
583
+
584
+ Later license versions may give you additional or different
585
+ permissions. However, no additional obligations are imposed on any
586
+ author or copyright holder as a result of your choosing to follow a
587
+ later version.
588
+
589
+ 15. Disclaimer of Warranty.
590
+
591
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592
+ APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593
+ HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594
+ OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595
+ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596
+ PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597
+ IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598
+ ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599
+
600
+ 16. Limitation of Liability.
601
+
602
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603
+ WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604
+ THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605
+ GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606
+ USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607
+ DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608
+ PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609
+ EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610
+ SUCH DAMAGES.
611
+
612
+ 17. Interpretation of Sections 15 and 16.
613
+
614
+ If the disclaimer of warranty and limitation of liability provided
615
+ above cannot be given local legal effect according to their terms,
616
+ reviewing courts shall apply local law that most closely approximates
617
+ an absolute waiver of all civil liability in connection with the
618
+ Program, unless a warranty or assumption of liability accompanies a
619
+ copy of the Program in return for a fee.
620
+
621
+ END OF TERMS AND CONDITIONS
modules_forge/packages/huggingface_guess/README.md ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # HuggingFace Guess
2
+ A simple tool to guess an HuggingFace repo URL from a state dict.
3
+
4
+ > The main model detection logics are extracted from **Diffusers** and stolen from **ComfyUI**.
5
+
6
+ <br>
7
+
8
+ - This repo does almost the same thing as the following code, but a bit stronger and more robust.
9
+
10
+ ```py
11
+ from diffusers.loaders.single_file_utils import fetch_diffusers_config
12
+ ```
13
+
14
+ - The following code will print `runwayml/stable-diffusion-v1-5`
15
+
16
+ ```py
17
+ import safetensors.torch as sf
18
+ import huggingface_guess
19
+
20
+
21
+ state_dict = sf.load_file("./realisticVisionV51_v51VAE.safetensors")
22
+ repo_name = huggingface_guess.guess_repo_name(state_dict)
23
+ print(repo_name)
24
+ ```
25
+
26
+ <br>
27
+
28
+ Then you can download (or prefetch configs) from HuggingFace to instantiate models and load weights.
modules_forge/packages/huggingface_guess/__init__.py ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Copyright (C) 2024 lllyasviel
3
+
4
+ This program is free software: you can redistribute it and/or modify
5
+ it under the terms of the GNU General Public License as published by
6
+ the Free Software Foundation, either version 3 of the License, or
7
+ (at your option) any later version.
8
+
9
+ This program is distributed in the hope that it will be useful,
10
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
11
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12
+ GNU General Public License for more details.
13
+
14
+ You should have received a copy of the GNU General Public License
15
+ along with this program. If not, see https://www.gnu.org/licenses/
16
+ """
17
+
18
+ from .detection import model_config_from_unet, unet_prefix_from_state_dict
19
+
20
+
21
+ def guess(state_dict):
22
+ unet_key_prefix = unet_prefix_from_state_dict(state_dict)
23
+ result = model_config_from_unet(
24
+ state_dict, unet_key_prefix, use_base_if_no_match=False
25
+ )
26
+ result.unet_key_prefix = [unet_key_prefix]
27
+ if "image_model" in result.unet_config:
28
+ del result.unet_config["image_model"]
29
+ if "audio_model" in result.unet_config:
30
+ del result.unet_config["audio_model"]
31
+ return result
32
+
33
+
34
+ def guess_repo_name(state_dict):
35
+ config = guess(state_dict)
36
+ assert config is not None
37
+ repo_id = config.huggingface_repo
38
+ return repo_id
modules_forge/packages/huggingface_guess/detection.py ADDED
@@ -0,0 +1,560 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # reference: https://github.com/comfyanonymous/ComfyUI/blob/v0.3.52/comfy/model_detection.py
2
+
3
+ import logging
4
+
5
+ from . import model_list
6
+
7
+
8
+ def count_blocks(state_dict_keys, prefix_string):
9
+ count = 0
10
+ while True:
11
+ c = False
12
+ for k in state_dict_keys:
13
+ if k.startswith(prefix_string.format(count)):
14
+ c = True
15
+ break
16
+ if c == False:
17
+ break
18
+ count += 1
19
+ return count
20
+
21
+
22
+ def calculate_transformer_depth(prefix, state_dict_keys, state_dict):
23
+ context_dim = None
24
+ use_linear_in_transformer = False
25
+
26
+ transformer_prefix = prefix + "1.transformer_blocks."
27
+ transformer_keys = sorted(list(filter(lambda a: a.startswith(transformer_prefix), state_dict_keys)))
28
+ if len(transformer_keys) > 0:
29
+ last_transformer_depth = count_blocks(state_dict_keys, transformer_prefix + "{}")
30
+ context_dim = state_dict["{}0.attn2.to_k.weight".format(transformer_prefix)].shape[1]
31
+ use_linear_in_transformer = len(state_dict["{}1.proj_in.weight".format(prefix)].shape) == 2
32
+ time_stack = "{}1.time_stack.0.attn1.to_q.weight".format(prefix) in state_dict or "{}1.time_mix_blocks.0.attn1.to_q.weight".format(prefix) in state_dict
33
+ time_stack_cross = "{}1.time_stack.0.attn2.to_q.weight".format(prefix) in state_dict or "{}1.time_mix_blocks.0.attn2.to_q.weight".format(prefix) in state_dict
34
+ return last_transformer_depth, context_dim, use_linear_in_transformer, time_stack, time_stack_cross
35
+ return None
36
+
37
+
38
+ def detect_unet_config(state_dict: dict, key_prefix: str):
39
+ state_dict_keys = list(state_dict.keys())
40
+
41
+ if "{}cap_embedder.1.weight".format(key_prefix) in state_dict_keys: # Lumina 2
42
+ dit_config = {}
43
+ dit_config["image_model"] = "lumina2"
44
+ dit_config["patch_size"] = 2
45
+ dit_config["in_channels"] = 16
46
+ w = state_dict["{}cap_embedder.1.weight".format(key_prefix)]
47
+ dit_config["dim"] = int(w.shape[0])
48
+ dit_config["cap_feat_dim"] = int(w.shape[1])
49
+ dit_config["n_layers"] = count_blocks(state_dict_keys, "{}layers.".format(key_prefix) + "{}.")
50
+ dit_config["qk_norm"] = True
51
+
52
+ if dit_config["dim"] == 2304: # Lumina 2
53
+ dit_config["n_heads"] = 24
54
+ dit_config["n_kv_heads"] = 8
55
+ dit_config["axes_dims"] = [32, 32, 32]
56
+ dit_config["axes_lens"] = [300, 512, 512]
57
+ dit_config["rope_theta"] = 10000.0
58
+ dit_config["ffn_dim_multiplier"] = 4.0
59
+ elif dit_config["dim"] == 3840: # Z-Image
60
+ dit_config["nunchaku"] = "{}layers.0.attention.to_out.0.qweight".format(key_prefix) in state_dict_keys
61
+ dit_config["n_heads"] = 30
62
+ dit_config["n_kv_heads"] = 30
63
+ dit_config["axes_dims"] = [32, 48, 48]
64
+ dit_config["axes_lens"] = [1536, 512, 512]
65
+ dit_config["rope_theta"] = 256.0
66
+ dit_config["ffn_dim_multiplier"] = 8.0 / 3.0
67
+ dit_config["z_image_modulation"] = True
68
+ dit_config["time_scale"] = 1000.0
69
+ if "{}cap_pad_token".format(key_prefix) in state_dict_keys:
70
+ dit_config["pad_tokens_multiple"] = 32
71
+
72
+ return dit_config
73
+
74
+ if "{}head.modulation".format(key_prefix) in state_dict_keys: # Wan 2.1
75
+ dit_config = {}
76
+ dit_config["image_model"] = "wan2.1"
77
+ dim = state_dict["{}head.modulation".format(key_prefix)].shape[-1]
78
+ out_dim = state_dict["{}head.head.weight".format(key_prefix)].shape[0] // 4
79
+ dit_config["dim"] = int(dim)
80
+ dit_config["out_dim"] = int(out_dim)
81
+ dit_config["num_heads"] = int(dim // 128)
82
+ dit_config["ffn_dim"] = int(state_dict["{}blocks.0.ffn.0.weight".format(key_prefix)].shape[0])
83
+ dit_config["num_layers"] = count_blocks(state_dict_keys, "{}blocks.".format(key_prefix) + "{}.")
84
+ dit_config["patch_size"] = (1, 2, 2)
85
+ dit_config["freq_dim"] = 256
86
+ dit_config["window_size"] = (-1, -1)
87
+ dit_config["qk_norm"] = True
88
+ dit_config["cross_attn_norm"] = True
89
+ dit_config["eps"] = 1e-6
90
+ dit_config["in_dim"] = int(state_dict["{}patch_embedding.weight".format(key_prefix)].shape[1])
91
+ if "{}img_emb.proj.0.bias".format(key_prefix) in state_dict_keys:
92
+ dit_config["model_type"] = "i2v"
93
+ else:
94
+ dit_config["model_type"] = "t2v"
95
+ flf_weight = state_dict.get("{}img_emb.emb_pos".format(key_prefix))
96
+ if flf_weight is not None:
97
+ dit_config["flf_pos_embed_token_number"] = flf_weight.shape[1]
98
+ return dit_config
99
+
100
+ if "{}single_transformer_blocks.0.mlp_fc1.qweight".format(key_prefix) in state_dict_keys: # SVDQ
101
+ dit_config = {"nunchaku": True}
102
+ dit_config["axes_dim"] = [16, 56, 56]
103
+ dit_config["context_in_dim"] = 4096
104
+ dit_config["depth"] = 19
105
+ dit_config["depth_single_blocks"] = 38
106
+ dit_config["disable_unet_model_creation"] = True
107
+ dit_config["guidance_embed"] = True
108
+ dit_config["hidden_size"] = 3072
109
+ dit_config["image_model"] = "flux"
110
+ dit_config["in_channels"] = 16
111
+ dit_config["mlp_ratio"] = 4.0
112
+ dit_config["num_heads"] = 24
113
+ dit_config["out_channels"] = 16
114
+ dit_config["patch_size"] = 2
115
+ dit_config["qkv_bias"] = True
116
+ dit_config["theta"] = 10000
117
+ dit_config["vec_in_dim"] = 768
118
+ return dit_config
119
+
120
+ if "{}double_blocks.0.img_attn.norm.key_norm.scale".format(key_prefix) in state_dict_keys and "{}img_in.weight".format(key_prefix) in state_dict_keys: # Flux
121
+ dit_config = {}
122
+ dit_config["image_model"] = "flux"
123
+ dit_config["in_channels"] = 16
124
+ patch_size = 2
125
+ dit_config["patch_size"] = patch_size
126
+ in_key = "{}img_in.weight".format(key_prefix)
127
+ if in_key in state_dict_keys:
128
+ dit_config["in_channels"] = state_dict[in_key].shape[1] // (patch_size * patch_size)
129
+ dit_config["out_channels"] = 16
130
+ vec_in_key = "{}vector_in.in_layer.weight".format(key_prefix)
131
+ if vec_in_key in state_dict_keys:
132
+ dit_config["vec_in_dim"] = state_dict[vec_in_key].shape[1]
133
+ dit_config["context_in_dim"] = 4096
134
+ dit_config["hidden_size"] = 3072
135
+ dit_config["mlp_ratio"] = 4.0
136
+ dit_config["num_heads"] = 24
137
+ dit_config["depth"] = count_blocks(state_dict_keys, "{}double_blocks.".format(key_prefix) + "{}.")
138
+ dit_config["depth_single_blocks"] = count_blocks(state_dict_keys, "{}single_blocks.".format(key_prefix) + "{}.")
139
+ dit_config["axes_dim"] = [16, 56, 56]
140
+ dit_config["theta"] = 10000
141
+ dit_config["qkv_bias"] = True
142
+ if "{}distilled_guidance_layer.0.norms.0.scale".format(key_prefix) in state_dict_keys or "{}distilled_guidance_layer.norms.0.scale".format(key_prefix) in state_dict_keys: # Chroma
143
+ dit_config["image_model"] = "chroma"
144
+ dit_config["in_channels"] = 64
145
+ dit_config["out_channels"] = 64
146
+ dit_config["in_dim"] = 64
147
+ dit_config["out_dim"] = 3072
148
+ dit_config["hidden_dim"] = 5120
149
+ dit_config["n_layers"] = 5
150
+ else:
151
+ dit_config["guidance_embed"] = "{}guidance_in.in_layer.weight".format(key_prefix) in state_dict_keys
152
+ return dit_config
153
+
154
+ if "{}txt_norm.weight".format(key_prefix) in state_dict_keys: # Qwen Image
155
+ _qweight: bool = "{}transformer_blocks.0.attn.to_qkv.qweight".format(key_prefix) in state_dict_keys
156
+ dit_config = {"nunchaku": _qweight}
157
+ dit_config["image_model"] = "qwen_image"
158
+ dit_config["in_channels"] = state_dict["{}img_in.weight".format(key_prefix)].shape[1]
159
+ dit_config["num_layers"] = count_blocks(state_dict_keys, "{}transformer_blocks.".format(key_prefix) + "{}.")
160
+ return dit_config
161
+
162
+ if "{}input_blocks.0.0.weight".format(key_prefix) not in state_dict_keys:
163
+ return None
164
+
165
+ unet_config = {
166
+ "use_checkpoint": False,
167
+ "image_size": 32,
168
+ "use_spatial_transformer": True,
169
+ "legacy": False,
170
+ }
171
+
172
+ y_input = "{}label_emb.0.0.weight".format(key_prefix)
173
+ if y_input in state_dict_keys:
174
+ unet_config["num_classes"] = "sequential"
175
+ unet_config["adm_in_channels"] = state_dict[y_input].shape[1]
176
+ else:
177
+ unet_config["adm_in_channels"] = None
178
+
179
+ model_channels = state_dict["{}input_blocks.0.0.weight".format(key_prefix)].shape[0]
180
+ in_channels = state_dict["{}input_blocks.0.0.weight".format(key_prefix)].shape[1]
181
+
182
+ out_key = "{}out.2.weight".format(key_prefix)
183
+ if out_key in state_dict:
184
+ out_channels = state_dict[out_key].shape[0]
185
+ else:
186
+ out_channels = 4
187
+
188
+ num_res_blocks = []
189
+ channel_mult = []
190
+ transformer_depth = []
191
+ transformer_depth_output = []
192
+ context_dim = None
193
+ use_linear_in_transformer = False
194
+
195
+ video_model = False
196
+
197
+ current_res = 1
198
+ count = 0
199
+
200
+ last_res_blocks = 0
201
+ last_channel_mult = 0
202
+
203
+ input_block_count = count_blocks(state_dict_keys, "{}input_blocks".format(key_prefix) + ".{}.")
204
+ for count in range(input_block_count):
205
+ prefix = "{}input_blocks.{}.".format(key_prefix, count)
206
+ prefix_output = "{}output_blocks.{}.".format(key_prefix, input_block_count - count - 1)
207
+
208
+ block_keys = sorted(list(filter(lambda a: a.startswith(prefix), state_dict_keys)))
209
+ if len(block_keys) == 0:
210
+ break
211
+
212
+ block_keys_output = sorted(list(filter(lambda a: a.startswith(prefix_output), state_dict_keys)))
213
+
214
+ if "{}0.op.weight".format(prefix) in block_keys: # new layer
215
+ num_res_blocks.append(last_res_blocks)
216
+ channel_mult.append(last_channel_mult)
217
+
218
+ current_res *= 2
219
+ last_res_blocks = 0
220
+ last_channel_mult = 0
221
+ out = calculate_transformer_depth(prefix_output, state_dict_keys, state_dict)
222
+ if out is not None:
223
+ transformer_depth_output.append(out[0])
224
+ else:
225
+ transformer_depth_output.append(0)
226
+ else:
227
+ res_block_prefix = "{}0.in_layers.0.weight".format(prefix)
228
+ if res_block_prefix in block_keys:
229
+ last_res_blocks += 1
230
+ last_channel_mult = state_dict["{}0.out_layers.3.weight".format(prefix)].shape[0] // model_channels
231
+
232
+ out = calculate_transformer_depth(prefix, state_dict_keys, state_dict)
233
+ if out is not None:
234
+ transformer_depth.append(out[0])
235
+ if context_dim is None:
236
+ context_dim = out[1]
237
+ use_linear_in_transformer = out[2]
238
+ video_model = out[3]
239
+ else:
240
+ transformer_depth.append(0)
241
+
242
+ res_block_prefix = "{}0.in_layers.0.weight".format(prefix_output)
243
+ if res_block_prefix in block_keys_output:
244
+ out = calculate_transformer_depth(prefix_output, state_dict_keys, state_dict)
245
+ if out is not None:
246
+ transformer_depth_output.append(out[0])
247
+ else:
248
+ transformer_depth_output.append(0)
249
+
250
+ num_res_blocks.append(last_res_blocks)
251
+ channel_mult.append(last_channel_mult)
252
+ if "{}middle_block.1.proj_in.weight".format(key_prefix) in state_dict_keys:
253
+ transformer_depth_middle = count_blocks(state_dict_keys, "{}middle_block.1.transformer_blocks.".format(key_prefix) + "{}")
254
+ elif "{}middle_block.0.in_layers.0.weight".format(key_prefix) in state_dict_keys:
255
+ transformer_depth_middle = -1
256
+ else:
257
+ transformer_depth_middle = -2
258
+
259
+ unet_config["in_channels"] = in_channels
260
+ unet_config["out_channels"] = out_channels
261
+ unet_config["model_channels"] = model_channels
262
+ unet_config["num_res_blocks"] = num_res_blocks
263
+ unet_config["transformer_depth"] = transformer_depth
264
+ unet_config["transformer_depth_output"] = transformer_depth_output
265
+ unet_config["channel_mult"] = channel_mult
266
+ unet_config["transformer_depth_middle"] = transformer_depth_middle
267
+ unet_config["use_linear_in_transformer"] = use_linear_in_transformer
268
+ unet_config["context_dim"] = context_dim
269
+
270
+ assert not video_model
271
+ unet_config["use_temporal_resblock"] = False
272
+ unet_config["use_temporal_attention"] = False
273
+
274
+ return unet_config
275
+
276
+
277
+ def model_config_from_unet_config(unet_config, state_dict=None):
278
+ for model_config in model_list.models:
279
+ if model_config.matches(unet_config, state_dict):
280
+ return model_config(unet_config)
281
+
282
+ logging.error("no match {}".format(unet_config))
283
+ return None
284
+
285
+
286
+ def model_config_from_unet(state_dict, unet_key_prefix, use_base_if_no_match=False):
287
+ unet_config = detect_unet_config(state_dict, unet_key_prefix)
288
+ if unet_config is None:
289
+ return None
290
+ model_config = model_config_from_unet_config(unet_config, state_dict)
291
+ if model_config is None and use_base_if_no_match:
292
+ return model_list.BASE(unet_config)
293
+ else:
294
+ return model_config
295
+
296
+
297
+ def top_candidate(state_dict, candidates):
298
+ counts = {k: 0 for k in candidates}
299
+ for k in state_dict:
300
+ for c in candidates:
301
+ if k.startswith(c):
302
+ counts[c] += 1
303
+ break
304
+ top = max(counts, key=counts.get)
305
+ return top, counts[top]
306
+
307
+
308
+ def unet_prefix_from_state_dict(state_dict):
309
+ candidates = [
310
+ "model.diffusion_model.", # ldm/sgm models
311
+ "model.model.", # audio models
312
+ "net.", # cosmos
313
+ ]
314
+ counts = {k: 0 for k in candidates}
315
+ for k in state_dict:
316
+ for c in candidates:
317
+ if k.startswith(c):
318
+ counts[c] += 1
319
+ break
320
+
321
+ top = max(counts, key=counts.get)
322
+ if counts[top] > 5:
323
+ return top
324
+ else:
325
+ return "model." # etc.
326
+
327
+
328
+ def convert_config(unet_config):
329
+ new_config = unet_config.copy()
330
+ num_res_blocks = new_config.get("num_res_blocks", None)
331
+ channel_mult = new_config.get("channel_mult", None)
332
+
333
+ if isinstance(num_res_blocks, int):
334
+ num_res_blocks = len(channel_mult) * [num_res_blocks]
335
+
336
+ if "attention_resolutions" in new_config:
337
+ attention_resolutions = new_config.pop("attention_resolutions")
338
+ transformer_depth = new_config.get("transformer_depth", None)
339
+ transformer_depth_middle = new_config.get("transformer_depth_middle", None)
340
+
341
+ if isinstance(transformer_depth, int):
342
+ transformer_depth = len(channel_mult) * [transformer_depth]
343
+ if transformer_depth_middle is None:
344
+ transformer_depth_middle = transformer_depth[-1]
345
+ t_in = []
346
+ t_out = []
347
+ s = 1
348
+ for i in range(len(num_res_blocks)):
349
+ res = num_res_blocks[i]
350
+ d = 0
351
+ if s in attention_resolutions:
352
+ d = transformer_depth[i]
353
+
354
+ t_in += [d] * res
355
+ t_out += [d] * (res + 1)
356
+ s *= 2
357
+ transformer_depth = t_in
358
+ new_config["transformer_depth"] = t_in
359
+ new_config["transformer_depth_output"] = t_out
360
+ new_config["transformer_depth_middle"] = transformer_depth_middle
361
+
362
+ new_config["num_res_blocks"] = num_res_blocks
363
+ return new_config
364
+
365
+
366
+ def unet_config_from_diffusers_unet(state_dict, dtype=None):
367
+ match = {}
368
+ transformer_depth = []
369
+
370
+ attn_res = 1
371
+ down_blocks = count_blocks(state_dict, "down_blocks.{}")
372
+ for i in range(down_blocks):
373
+ attn_blocks = count_blocks(state_dict, "down_blocks.{}.attentions.".format(i) + "{}")
374
+ res_blocks = count_blocks(state_dict, "down_blocks.{}.resnets.".format(i) + "{}")
375
+ for ab in range(attn_blocks):
376
+ transformer_count = count_blocks(
377
+ state_dict,
378
+ "down_blocks.{}.attentions.{}.transformer_blocks.".format(i, ab) + "{}",
379
+ )
380
+ transformer_depth.append(transformer_count)
381
+ if transformer_count > 0:
382
+ match["context_dim"] = state_dict["down_blocks.{}.attentions.{}.transformer_blocks.0.attn2.to_k.weight".format(i, ab)].shape[1]
383
+
384
+ attn_res *= 2
385
+ if attn_blocks == 0:
386
+ for i in range(res_blocks):
387
+ transformer_depth.append(0)
388
+
389
+ match["transformer_depth"] = transformer_depth
390
+
391
+ match["model_channels"] = state_dict["conv_in.weight"].shape[0]
392
+ match["in_channels"] = state_dict["conv_in.weight"].shape[1]
393
+ match["adm_in_channels"] = None
394
+ if "class_embedding.linear_1.weight" in state_dict:
395
+ match["adm_in_channels"] = state_dict["class_embedding.linear_1.weight"].shape[1]
396
+ elif "add_embedding.linear_1.weight" in state_dict:
397
+ match["adm_in_channels"] = state_dict["add_embedding.linear_1.weight"].shape[1]
398
+
399
+ SDXL = {
400
+ "use_checkpoint": False,
401
+ "image_size": 32,
402
+ "out_channels": 4,
403
+ "use_spatial_transformer": True,
404
+ "legacy": False,
405
+ "num_classes": "sequential",
406
+ "adm_in_channels": 2816,
407
+ "dtype": dtype,
408
+ "in_channels": 4,
409
+ "model_channels": 320,
410
+ "num_res_blocks": [2, 2, 2],
411
+ "transformer_depth": [0, 0, 2, 2, 10, 10],
412
+ "channel_mult": [1, 2, 4],
413
+ "transformer_depth_middle": 10,
414
+ "use_linear_in_transformer": True,
415
+ "context_dim": 2048,
416
+ "num_head_channels": 64,
417
+ "transformer_depth_output": [0, 0, 0, 2, 2, 2, 10, 10, 10],
418
+ "use_temporal_attention": False,
419
+ "use_temporal_resblock": False,
420
+ }
421
+
422
+ SDXL_refiner = {
423
+ "use_checkpoint": False,
424
+ "image_size": 32,
425
+ "out_channels": 4,
426
+ "use_spatial_transformer": True,
427
+ "legacy": False,
428
+ "num_classes": "sequential",
429
+ "adm_in_channels": 2560,
430
+ "dtype": dtype,
431
+ "in_channels": 4,
432
+ "model_channels": 384,
433
+ "num_res_blocks": [2, 2, 2, 2],
434
+ "transformer_depth": [0, 0, 4, 4, 4, 4, 0, 0],
435
+ "channel_mult": [1, 2, 4, 4],
436
+ "transformer_depth_middle": 4,
437
+ "use_linear_in_transformer": True,
438
+ "context_dim": 1280,
439
+ "num_head_channels": 64,
440
+ "transformer_depth_output": [0, 0, 0, 4, 4, 4, 4, 4, 4, 0, 0, 0],
441
+ "use_temporal_attention": False,
442
+ "use_temporal_resblock": False,
443
+ }
444
+
445
+ SD15 = {
446
+ "use_checkpoint": False,
447
+ "image_size": 32,
448
+ "out_channels": 4,
449
+ "use_spatial_transformer": True,
450
+ "legacy": False,
451
+ "adm_in_channels": None,
452
+ "dtype": dtype,
453
+ "in_channels": 4,
454
+ "model_channels": 320,
455
+ "num_res_blocks": [2, 2, 2, 2],
456
+ "transformer_depth": [1, 1, 1, 1, 1, 1, 0, 0],
457
+ "channel_mult": [1, 2, 4, 4],
458
+ "transformer_depth_middle": 1,
459
+ "use_linear_in_transformer": False,
460
+ "context_dim": 768,
461
+ "num_heads": 8,
462
+ "transformer_depth_output": [1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0],
463
+ "use_temporal_attention": False,
464
+ "use_temporal_resblock": False,
465
+ }
466
+
467
+ SDXL_mid_cnet = {
468
+ "use_checkpoint": False,
469
+ "image_size": 32,
470
+ "out_channels": 4,
471
+ "use_spatial_transformer": True,
472
+ "legacy": False,
473
+ "num_classes": "sequential",
474
+ "adm_in_channels": 2816,
475
+ "dtype": dtype,
476
+ "in_channels": 4,
477
+ "model_channels": 320,
478
+ "num_res_blocks": [2, 2, 2],
479
+ "transformer_depth": [0, 0, 0, 0, 1, 1],
480
+ "channel_mult": [1, 2, 4],
481
+ "transformer_depth_middle": 1,
482
+ "use_linear_in_transformer": True,
483
+ "context_dim": 2048,
484
+ "num_head_channels": 64,
485
+ "transformer_depth_output": [0, 0, 0, 0, 0, 0, 1, 1, 1],
486
+ "use_temporal_attention": False,
487
+ "use_temporal_resblock": False,
488
+ }
489
+
490
+ SDXL_small_cnet = {
491
+ "use_checkpoint": False,
492
+ "image_size": 32,
493
+ "out_channels": 4,
494
+ "use_spatial_transformer": True,
495
+ "legacy": False,
496
+ "num_classes": "sequential",
497
+ "adm_in_channels": 2816,
498
+ "dtype": dtype,
499
+ "in_channels": 4,
500
+ "model_channels": 320,
501
+ "num_res_blocks": [2, 2, 2],
502
+ "transformer_depth": [0, 0, 0, 0, 0, 0],
503
+ "channel_mult": [1, 2, 4],
504
+ "transformer_depth_middle": 0,
505
+ "use_linear_in_transformer": True,
506
+ "num_head_channels": 64,
507
+ "context_dim": 1,
508
+ "transformer_depth_output": [0, 0, 0, 0, 0, 0, 0, 0, 0],
509
+ "use_temporal_attention": False,
510
+ "use_temporal_resblock": False,
511
+ }
512
+
513
+ SDXL_diffusers_inpaint = {
514
+ "use_checkpoint": False,
515
+ "image_size": 32,
516
+ "out_channels": 4,
517
+ "use_spatial_transformer": True,
518
+ "legacy": False,
519
+ "num_classes": "sequential",
520
+ "adm_in_channels": 2816,
521
+ "dtype": dtype,
522
+ "in_channels": 9,
523
+ "model_channels": 320,
524
+ "num_res_blocks": [2, 2, 2],
525
+ "transformer_depth": [0, 0, 2, 2, 10, 10],
526
+ "channel_mult": [1, 2, 4],
527
+ "transformer_depth_middle": 10,
528
+ "use_linear_in_transformer": True,
529
+ "context_dim": 2048,
530
+ "num_head_channels": 64,
531
+ "transformer_depth_output": [0, 0, 0, 2, 2, 2, 10, 10, 10],
532
+ "use_temporal_attention": False,
533
+ "use_temporal_resblock": False,
534
+ }
535
+
536
+ supported_models = [
537
+ SD15,
538
+ SDXL,
539
+ SDXL_refiner,
540
+ SDXL_mid_cnet,
541
+ SDXL_small_cnet,
542
+ SDXL_diffusers_inpaint,
543
+ ]
544
+
545
+ for unet_config in supported_models:
546
+ matches = True
547
+ for k in match:
548
+ if match[k] != unet_config[k]:
549
+ matches = False
550
+ break
551
+ if matches:
552
+ return convert_config(unet_config)
553
+ return None
554
+
555
+
556
+ def model_config_from_diffusers_unet(state_dict):
557
+ unet_config = unet_config_from_diffusers_unet(state_dict)
558
+ if unet_config is not None:
559
+ return model_config_from_unet_config(unet_config)
560
+ return None
modules_forge/packages/huggingface_guess/diffusers_convert.py ADDED
@@ -0,0 +1,280 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ import re
3
+
4
+ import torch
5
+
6
+ # conversion code from https://github.com/huggingface/diffusers/blob/main/scripts/convert_diffusers_to_original_stable_diffusion.py
7
+
8
+ # =============== #
9
+ # UNet Conversion #
10
+ # =============== #
11
+
12
+ unet_conversion_map = [
13
+ # (stable-diffusion, HF Diffusers)
14
+ ("time_embed.0.weight", "time_embedding.linear_1.weight"),
15
+ ("time_embed.0.bias", "time_embedding.linear_1.bias"),
16
+ ("time_embed.2.weight", "time_embedding.linear_2.weight"),
17
+ ("time_embed.2.bias", "time_embedding.linear_2.bias"),
18
+ ("input_blocks.0.0.weight", "conv_in.weight"),
19
+ ("input_blocks.0.0.bias", "conv_in.bias"),
20
+ ("out.0.weight", "conv_norm_out.weight"),
21
+ ("out.0.bias", "conv_norm_out.bias"),
22
+ ("out.2.weight", "conv_out.weight"),
23
+ ("out.2.bias", "conv_out.bias"),
24
+ ]
25
+
26
+ unet_conversion_map_resnet = [
27
+ # (stable-diffusion, HF Diffusers)
28
+ ("in_layers.0", "norm1"),
29
+ ("in_layers.2", "conv1"),
30
+ ("out_layers.0", "norm2"),
31
+ ("out_layers.3", "conv2"),
32
+ ("emb_layers.1", "time_emb_proj"),
33
+ ("skip_connection", "conv_shortcut"),
34
+ ]
35
+
36
+ unet_conversion_map_layer = []
37
+ # hardcoded number of downblocks and resnets/attentions...
38
+ # would need smarter logic for other networks.
39
+ for i in range(4):
40
+ # loop over downblocks/upblocks
41
+
42
+ for j in range(2):
43
+ # loop over resnets/attentions for downblocks
44
+ hf_down_res_prefix = f"down_blocks.{i}.resnets.{j}."
45
+ sd_down_res_prefix = f"input_blocks.{3 * i + j + 1}.0."
46
+ unet_conversion_map_layer.append((sd_down_res_prefix, hf_down_res_prefix))
47
+
48
+ if i < 3:
49
+ # no attention layers in down_blocks.3
50
+ hf_down_atn_prefix = f"down_blocks.{i}.attentions.{j}."
51
+ sd_down_atn_prefix = f"input_blocks.{3 * i + j + 1}.1."
52
+ unet_conversion_map_layer.append((sd_down_atn_prefix, hf_down_atn_prefix))
53
+
54
+ for j in range(3):
55
+ # loop over resnets/attentions for upblocks
56
+ hf_up_res_prefix = f"up_blocks.{i}.resnets.{j}."
57
+ sd_up_res_prefix = f"output_blocks.{3 * i + j}.0."
58
+ unet_conversion_map_layer.append((sd_up_res_prefix, hf_up_res_prefix))
59
+
60
+ if i > 0:
61
+ # no attention layers in up_blocks.0
62
+ hf_up_atn_prefix = f"up_blocks.{i}.attentions.{j}."
63
+ sd_up_atn_prefix = f"output_blocks.{3 * i + j}.1."
64
+ unet_conversion_map_layer.append((sd_up_atn_prefix, hf_up_atn_prefix))
65
+
66
+ if i < 3:
67
+ # no downsample in down_blocks.3
68
+ hf_downsample_prefix = f"down_blocks.{i}.downsamplers.0.conv."
69
+ sd_downsample_prefix = f"input_blocks.{3 * (i + 1)}.0.op."
70
+ unet_conversion_map_layer.append((sd_downsample_prefix, hf_downsample_prefix))
71
+
72
+ # no upsample in up_blocks.3
73
+ hf_upsample_prefix = f"up_blocks.{i}.upsamplers.0."
74
+ sd_upsample_prefix = f"output_blocks.{3 * i + 2}.{1 if i == 0 else 2}."
75
+ unet_conversion_map_layer.append((sd_upsample_prefix, hf_upsample_prefix))
76
+
77
+ hf_mid_atn_prefix = "mid_block.attentions.0."
78
+ sd_mid_atn_prefix = "middle_block.1."
79
+ unet_conversion_map_layer.append((sd_mid_atn_prefix, hf_mid_atn_prefix))
80
+
81
+ for j in range(2):
82
+ hf_mid_res_prefix = f"mid_block.resnets.{j}."
83
+ sd_mid_res_prefix = f"middle_block.{2 * j}."
84
+ unet_conversion_map_layer.append((sd_mid_res_prefix, hf_mid_res_prefix))
85
+
86
+
87
+ def convert_unet_state_dict(unet_state_dict):
88
+ # buyer beware: this is a *brittle* function,
89
+ # and correct output requires that all of these pieces interact in
90
+ # the exact order in which I have arranged them.
91
+ mapping = {k: k for k in unet_state_dict.keys()}
92
+ for sd_name, hf_name in unet_conversion_map:
93
+ mapping[hf_name] = sd_name
94
+ for k, v in mapping.items():
95
+ if "resnets" in k:
96
+ for sd_part, hf_part in unet_conversion_map_resnet:
97
+ v = v.replace(hf_part, sd_part)
98
+ mapping[k] = v
99
+ for k, v in mapping.items():
100
+ for sd_part, hf_part in unet_conversion_map_layer:
101
+ v = v.replace(hf_part, sd_part)
102
+ mapping[k] = v
103
+ new_state_dict = {v: unet_state_dict[k] for k, v in mapping.items()}
104
+ return new_state_dict
105
+
106
+
107
+ # ============== #
108
+ # VAE Conversion #
109
+ # ============== #
110
+
111
+ vae_conversion_map = [
112
+ # (stable-diffusion, HF Diffusers)
113
+ ("nin_shortcut", "conv_shortcut"),
114
+ ("norm_out", "conv_norm_out"),
115
+ ("mid.attn_1.", "mid_block.attentions.0."),
116
+ ]
117
+
118
+ for i in range(4):
119
+ # down_blocks have two resnets
120
+ for j in range(2):
121
+ hf_down_prefix = f"encoder.down_blocks.{i}.resnets.{j}."
122
+ sd_down_prefix = f"encoder.down.{i}.block.{j}."
123
+ vae_conversion_map.append((sd_down_prefix, hf_down_prefix))
124
+
125
+ if i < 3:
126
+ hf_downsample_prefix = f"down_blocks.{i}.downsamplers.0."
127
+ sd_downsample_prefix = f"down.{i}.downsample."
128
+ vae_conversion_map.append((sd_downsample_prefix, hf_downsample_prefix))
129
+
130
+ hf_upsample_prefix = f"up_blocks.{i}.upsamplers.0."
131
+ sd_upsample_prefix = f"up.{3 - i}.upsample."
132
+ vae_conversion_map.append((sd_upsample_prefix, hf_upsample_prefix))
133
+
134
+ # up_blocks have three resnets
135
+ # also, up blocks in hf are numbered in reverse from sd
136
+ for j in range(3):
137
+ hf_up_prefix = f"decoder.up_blocks.{i}.resnets.{j}."
138
+ sd_up_prefix = f"decoder.up.{3 - i}.block.{j}."
139
+ vae_conversion_map.append((sd_up_prefix, hf_up_prefix))
140
+
141
+ # this part accounts for mid blocks in both the encoder and the decoder
142
+ for i in range(2):
143
+ hf_mid_res_prefix = f"mid_block.resnets.{i}."
144
+ sd_mid_res_prefix = f"mid.block_{i + 1}."
145
+ vae_conversion_map.append((sd_mid_res_prefix, hf_mid_res_prefix))
146
+
147
+ vae_conversion_map_attn = [
148
+ # (stable-diffusion, HF Diffusers)
149
+ ("norm.", "group_norm."),
150
+ ("q.", "query."),
151
+ ("k.", "key."),
152
+ ("v.", "value."),
153
+ ("q.", "to_q."),
154
+ ("k.", "to_k."),
155
+ ("v.", "to_v."),
156
+ ("proj_out.", "to_out.0."),
157
+ ("proj_out.", "proj_attn."),
158
+ ]
159
+
160
+
161
+ def reshape_weight_for_sd(w):
162
+ # convert HF linear weights to SD conv2d weights
163
+ return w.reshape(*w.shape, 1, 1)
164
+
165
+
166
+ def convert_vae_state_dict(vae_state_dict):
167
+ mapping = {k: k for k in vae_state_dict.keys()}
168
+ for k, v in mapping.items():
169
+ for sd_part, hf_part in vae_conversion_map:
170
+ v = v.replace(hf_part, sd_part)
171
+ mapping[k] = v
172
+ for k, v in mapping.items():
173
+ if "attentions" in k:
174
+ for sd_part, hf_part in vae_conversion_map_attn:
175
+ v = v.replace(hf_part, sd_part)
176
+ mapping[k] = v
177
+ new_state_dict = {v: vae_state_dict[k] for k, v in mapping.items()}
178
+ weights_to_convert = ["q", "k", "v", "proj_out"]
179
+ for k, v in new_state_dict.items():
180
+ for weight_name in weights_to_convert:
181
+ if f"mid.attn_1.{weight_name}.weight" in k:
182
+ logging.debug(f"Reshaping {k} for SD format")
183
+ new_state_dict[k] = reshape_weight_for_sd(v)
184
+ return new_state_dict
185
+
186
+
187
+ # =========================#
188
+ # Text Encoder Conversion #
189
+ # =========================#
190
+
191
+
192
+ textenc_conversion_lst = [
193
+ # (stable-diffusion, HF Diffusers)
194
+ ("resblocks.", "text_model.encoder.layers."),
195
+ ("ln_1", "layer_norm1"),
196
+ ("ln_2", "layer_norm2"),
197
+ (".c_fc.", ".fc1."),
198
+ (".c_proj.", ".fc2."),
199
+ (".attn", ".self_attn"),
200
+ ("ln_final.", "transformer.text_model.final_layer_norm."),
201
+ (
202
+ "token_embedding.weight",
203
+ "transformer.text_model.embeddings.token_embedding.weight",
204
+ ),
205
+ (
206
+ "positional_embedding",
207
+ "transformer.text_model.embeddings.position_embedding.weight",
208
+ ),
209
+ ]
210
+ protected = {re.escape(x[1]): x[0] for x in textenc_conversion_lst}
211
+ textenc_pattern = re.compile("|".join(protected.keys()))
212
+
213
+ # Ordering is from https://github.com/pytorch/pytorch/blob/master/test/cpp/api/modules.cpp
214
+ code2idx = {"q": 0, "k": 1, "v": 2}
215
+
216
+
217
+ # This function exists because at the time of writing torch.cat can't do fp8 with cuda
218
+ def cat_tensors(tensors):
219
+ x = 0
220
+ for t in tensors:
221
+ x += t.shape[0]
222
+
223
+ shape = [x] + list(tensors[0].shape)[1:]
224
+ out = torch.empty(shape, device=tensors[0].device, dtype=tensors[0].dtype)
225
+
226
+ x = 0
227
+ for t in tensors:
228
+ out[x : x + t.shape[0]] = t
229
+ x += t.shape[0]
230
+
231
+ return out
232
+
233
+
234
+ def convert_text_enc_state_dict_v20(text_enc_dict, prefix=""):
235
+ new_state_dict = {}
236
+ capture_qkv_weight = {}
237
+ capture_qkv_bias = {}
238
+ for k, v in text_enc_dict.items():
239
+ if not k.startswith(prefix):
240
+ continue
241
+ if k.endswith(".self_attn.q_proj.weight") or k.endswith(".self_attn.k_proj.weight") or k.endswith(".self_attn.v_proj.weight"):
242
+ k_pre = k[: -len(".q_proj.weight")]
243
+ k_code = k[-len("q_proj.weight")]
244
+ if k_pre not in capture_qkv_weight:
245
+ capture_qkv_weight[k_pre] = [None, None, None]
246
+ capture_qkv_weight[k_pre][code2idx[k_code]] = v
247
+ continue
248
+
249
+ if k.endswith(".self_attn.q_proj.bias") or k.endswith(".self_attn.k_proj.bias") or k.endswith(".self_attn.v_proj.bias"):
250
+ k_pre = k[: -len(".q_proj.bias")]
251
+ k_code = k[-len("q_proj.bias")]
252
+ if k_pre not in capture_qkv_bias:
253
+ capture_qkv_bias[k_pre] = [None, None, None]
254
+ capture_qkv_bias[k_pre][code2idx[k_code]] = v
255
+ continue
256
+
257
+ text_proj = "transformer.text_projection.weight"
258
+ if k.endswith(text_proj):
259
+ new_state_dict[k.replace(text_proj, "text_projection")] = v.transpose(0, 1).contiguous()
260
+ else:
261
+ relabelled_key = textenc_pattern.sub(lambda m: protected[re.escape(m.group(0))], k)
262
+ new_state_dict[relabelled_key] = v
263
+
264
+ for k_pre, tensors in capture_qkv_weight.items():
265
+ if None in tensors:
266
+ raise Exception("CORRUPTED MODEL: one of the q-k-v values for the text encoder was missing")
267
+ relabelled_key = textenc_pattern.sub(lambda m: protected[re.escape(m.group(0))], k_pre)
268
+ new_state_dict[relabelled_key + ".in_proj_weight"] = cat_tensors(tensors)
269
+
270
+ for k_pre, tensors in capture_qkv_bias.items():
271
+ if None in tensors:
272
+ raise Exception("CORRUPTED MODEL: one of the q-k-v values for the text encoder was missing")
273
+ relabelled_key = textenc_pattern.sub(lambda m: protected[re.escape(m.group(0))], k_pre)
274
+ new_state_dict[relabelled_key + ".in_proj_bias"] = cat_tensors(tensors)
275
+
276
+ return new_state_dict
277
+
278
+
279
+ def convert_text_enc_state_dict(text_enc_dict):
280
+ return text_enc_dict
modules_forge/packages/huggingface_guess/latent.py ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # reference: https://github.com/comfyanonymous/ComfyUI/blob/v0.3.52/comfy/latent_formats.py
2
+
3
+ import torch
4
+
5
+
6
+ class LatentFormat:
7
+ scale_factor = 1.0
8
+ latent_channels = 4
9
+ latent_rgb_factors = None
10
+ latent_rgb_factors_bias = None
11
+ taesd_decoder_name = None
12
+
13
+ def process_in(self, latent):
14
+ return latent * self.scale_factor
15
+
16
+ def process_out(self, latent):
17
+ return latent / self.scale_factor
18
+
19
+
20
+ class SD15(LatentFormat):
21
+ def __init__(self, scale_factor=0.18215):
22
+ self.scale_factor = scale_factor
23
+ self.latent_rgb_factors = [
24
+ # R G B
25
+ [ 0.3512, 0.2297, 0.3227],
26
+ [ 0.3250, 0.4974, 0.2350],
27
+ [-0.2829, 0.1762, 0.2721],
28
+ [-0.2120, -0.2616, -0.7177],
29
+ ]
30
+ self.taesd_decoder_name = "taesd_decoder"
31
+
32
+
33
+ class SDXL(LatentFormat):
34
+ scale_factor = 0.13025
35
+
36
+ def __init__(self):
37
+ self.latent_rgb_factors = [
38
+ # R G B
39
+ [ 0.3651, 0.4232, 0.4341],
40
+ [-0.2533, -0.0042, 0.1068],
41
+ [ 0.1076, 0.1111, -0.0362],
42
+ [-0.3165, -0.2492, -0.2188],
43
+ ]
44
+ self.latent_rgb_factors_bias = [0.1084, -0.0175, -0.0011]
45
+ self.taesd_decoder_name = "taesdxl_decoder"
46
+
47
+
48
+ class Flux(LatentFormat):
49
+ latent_channels = 16
50
+
51
+ def __init__(self):
52
+ self.scale_factor = 0.3611
53
+ self.shift_factor = 0.1159
54
+ self.latent_rgb_factors = [
55
+ [-0.0346, 0.0244, 0.0681],
56
+ [ 0.0034, 0.0210, 0.0687],
57
+ [ 0.0275, -0.0668, -0.0433],
58
+ [-0.0174, 0.0160, 0.0617],
59
+ [ 0.0859, 0.0721, 0.0329],
60
+ [ 0.0004, 0.0383, 0.0115],
61
+ [ 0.0405, 0.0861, 0.0915],
62
+ [-0.0236, -0.0185, -0.0259],
63
+ [-0.0245, 0.0250, 0.1180],
64
+ [ 0.1008, 0.0755, -0.0421],
65
+ [-0.0515, 0.0201, 0.0011],
66
+ [ 0.0428, -0.0012, -0.0036],
67
+ [ 0.0817, 0.0765, 0.0749],
68
+ [-0.1264, -0.0522, -0.1103],
69
+ [-0.0280, -0.0881, -0.0499],
70
+ [-0.1262, -0.0982, -0.0778],
71
+ ]
72
+ self.latent_rgb_factors_bias = [-0.0329, -0.0718, -0.0851]
73
+ self.taesd_decoder_name = "taef1_decoder"
74
+
75
+ def process_in(self, latent):
76
+ return (latent - self.shift_factor) * self.scale_factor
77
+
78
+ def process_out(self, latent):
79
+ return (latent / self.scale_factor) + self.shift_factor
80
+
81
+
82
+ class Wan21(LatentFormat):
83
+ latent_channels = 16
84
+ latent_dimensions = 3
85
+
86
+ latent_rgb_factors = [
87
+ [-0.1299, -0.1692, 0.2932],
88
+ [ 0.0671, 0.0406, 0.0442],
89
+ [ 0.3568, 0.2548, 0.1747],
90
+ [ 0.0372, 0.2344, 0.1420],
91
+ [ 0.0313, 0.0189, -0.0328],
92
+ [ 0.0296, -0.0956, -0.0665],
93
+ [-0.3477, -0.4059, -0.2925],
94
+ [ 0.0166, 0.1902, 0.1975],
95
+ [-0.0412, 0.0267, -0.1364],
96
+ [-0.1293, 0.0740, 0.1636],
97
+ [ 0.0680, 0.3019, 0.1128],
98
+ [ 0.0032, 0.0581, 0.0639],
99
+ [-0.1251, 0.0927, 0.1699],
100
+ [ 0.0060, -0.0633, 0.0005],
101
+ [ 0.3477, 0.2275, 0.2950],
102
+ [ 0.1984, 0.0913, 0.1861],
103
+ ]
104
+ latent_rgb_factors_bias = [-0.1835, -0.0868, -0.3360]
105
+
106
+ def __init__(self):
107
+ self.scale_factor = 1.0
108
+ self.latents_mean = torch.tensor([-0.7571, -0.7089, -0.9113, 0.1075, -0.1745, 0.9653, -0.1517, 1.5508, 0.4134, -0.0715, 0.5517, -0.3632, -0.1922, -0.9497, 0.2503, -0.2921]).view(1, self.latent_channels, 1, 1, 1)
109
+ self.latents_std = torch.tensor([2.8184, 1.4541, 2.3275, 2.6558, 1.2196, 1.7708, 2.6052, 2.0743, 3.2687, 2.1526, 2.8652, 1.5579, 1.6382, 1.1253, 2.8251, 1.9160]).view(1, self.latent_channels, 1, 1, 1)
110
+
111
+ self.taesd_decoder_name = None
112
+
113
+ def process_in(self, latent):
114
+ latents_mean = self.latents_mean.to(latent.device, latent.dtype)
115
+ latents_std = self.latents_std.to(latent.device, latent.dtype)
116
+ return (latent - latents_mean) * self.scale_factor / latents_std
117
+
118
+ def process_out(self, latent):
119
+ latents_mean = self.latents_mean.to(latent.device, latent.dtype)
120
+ latents_std = self.latents_std.to(latent.device, latent.dtype)
121
+ return latent * latents_std / self.scale_factor + latents_mean
modules_forge/packages/huggingface_guess/model_list.py ADDED
@@ -0,0 +1,466 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # reference: https://github.com/comfyanonymous/ComfyUI/blob/v0.3.77/comfy/supported_models.py
2
+
3
+ from enum import Enum
4
+
5
+ import torch
6
+
7
+ from . import diffusers_convert, latent, utils
8
+
9
+
10
+ class ModelType(Enum):
11
+ EPS = 1
12
+ V_PREDICTION = 2
13
+ FLUX = 3
14
+ FLOW = 4
15
+
16
+
17
+ class BASE:
18
+ huggingface_repo = None
19
+ unet_config = {}
20
+ unet_extra_config = {
21
+ "num_heads": -1,
22
+ "num_head_channels": 64,
23
+ }
24
+
25
+ required_keys = {}
26
+
27
+ clip_prefix = []
28
+ clip_vision_prefix = None
29
+ noise_aug_config = None
30
+ sampling_settings = {}
31
+ latent_format = latent.LatentFormat
32
+ vae_key_prefix = ["first_stage_model."]
33
+ text_encoder_key_prefix = ["cond_stage_model."]
34
+ supported_inference_dtypes = [torch.float16, torch.bfloat16, torch.float32]
35
+
36
+ memory_usage_factor = 2.0
37
+
38
+ manual_cast_dtype = None
39
+ unet_target = "unet"
40
+ vae_target = "vae"
41
+
42
+ @classmethod
43
+ def matches(cls, unet_config, state_dict=None):
44
+ for k in cls.unet_config:
45
+ if k not in unet_config or cls.unet_config[k] != unet_config[k]:
46
+ return False
47
+ if state_dict is not None:
48
+ for k in cls.required_keys:
49
+ if k not in state_dict:
50
+ return False
51
+ return True
52
+
53
+ def model_type(self, state_dict):
54
+ return ModelType.EPS
55
+
56
+ def clip_target(self, state_dict: dict):
57
+ return {}
58
+
59
+ def inpaint_model(self):
60
+ return self.unet_config.get("in_channels", -1) > 4
61
+
62
+ def __init__(self, unet_config):
63
+ self.unet_config = unet_config.copy()
64
+ self.nunchaku: bool = self.unet_config.pop("nunchaku", False)
65
+ self.sampling_settings = self.sampling_settings.copy()
66
+ self.latent_format = self.latent_format()
67
+ for x in self.unet_extra_config:
68
+ self.unet_config[x] = self.unet_extra_config[x]
69
+
70
+ def process_clip_state_dict(self, state_dict):
71
+ replace_prefix = {k: "" for k in self.text_encoder_key_prefix}
72
+ return utils.state_dict_prefix_replace(state_dict, replace_prefix, filter_keys=True)
73
+
74
+ def process_unet_state_dict(self, state_dict):
75
+ return state_dict
76
+
77
+ def process_vae_state_dict(self, state_dict):
78
+ return state_dict
79
+
80
+ def process_clip_state_dict_for_saving(self, state_dict):
81
+ replace_prefix = {"": self.text_encoder_key_prefix[0]}
82
+ return utils.state_dict_prefix_replace(state_dict, replace_prefix)
83
+
84
+ def process_clip_vision_state_dict_for_saving(self, state_dict):
85
+ replace_prefix = {}
86
+ if self.clip_vision_prefix is not None:
87
+ replace_prefix[""] = self.clip_vision_prefix
88
+ return utils.state_dict_prefix_replace(state_dict, replace_prefix)
89
+
90
+ def process_unet_state_dict_for_saving(self, state_dict):
91
+ replace_prefix = {"": "model.diffusion_model."}
92
+ return utils.state_dict_prefix_replace(state_dict, replace_prefix)
93
+
94
+ def process_vae_state_dict_for_saving(self, state_dict):
95
+ replace_prefix = {"": self.vae_key_prefix[0]}
96
+ return utils.state_dict_prefix_replace(state_dict, replace_prefix)
97
+
98
+
99
+ class SD15(BASE):
100
+ huggingface_repo = "runwayml/stable-diffusion-v1-5"
101
+
102
+ unet_config = {
103
+ "context_dim": 768,
104
+ "model_channels": 320,
105
+ "use_linear_in_transformer": False,
106
+ "adm_in_channels": None,
107
+ "use_temporal_attention": False,
108
+ }
109
+
110
+ unet_extra_config = {
111
+ "num_heads": 8,
112
+ "num_head_channels": -1,
113
+ }
114
+
115
+ latent_format = latent.SD15
116
+ memory_usage_factor = 1.0
117
+
118
+ def process_clip_state_dict(self, state_dict):
119
+ k = list(state_dict.keys())
120
+ for x in k:
121
+ if x.startswith("cond_stage_model.transformer.") and not x.startswith("cond_stage_model.transformer.text_model."):
122
+ y = x.replace("cond_stage_model.transformer.", "cond_stage_model.transformer.text_model.")
123
+ state_dict[y] = state_dict.pop(x)
124
+
125
+ if "cond_stage_model.transformer.text_model.embeddings.position_ids" in state_dict:
126
+ ids = state_dict["cond_stage_model.transformer.text_model.embeddings.position_ids"]
127
+ if ids.dtype == torch.float32:
128
+ state_dict["cond_stage_model.transformer.text_model.embeddings.position_ids"] = ids.round()
129
+
130
+ replace_prefix = {"cond_stage_model.": "clip_l."}
131
+ return utils.state_dict_prefix_replace(state_dict, replace_prefix, filter_keys=True)
132
+
133
+ def process_clip_state_dict_for_saving(self, state_dict):
134
+ pop_keys = ["clip_l.transformer.text_projection.weight", "clip_l.logit_scale"]
135
+ for p in pop_keys:
136
+ if p in state_dict:
137
+ state_dict.pop(p)
138
+
139
+ replace_prefix = {"clip_l.": "cond_stage_model."}
140
+ return utils.state_dict_prefix_replace(state_dict, replace_prefix)
141
+
142
+ def clip_target(self, state_dict: dict):
143
+ return {"clip_l": "text_encoder"}
144
+
145
+
146
+ class SDXLRefiner(BASE):
147
+ huggingface_repo = "stabilityai/stable-diffusion-xl-refiner-1.0"
148
+
149
+ unet_config = {
150
+ "model_channels": 384,
151
+ "use_linear_in_transformer": True,
152
+ "context_dim": 1280,
153
+ "adm_in_channels": 2560,
154
+ "transformer_depth": [0, 0, 4, 4, 4, 4, 0, 0],
155
+ "use_temporal_attention": False,
156
+ }
157
+
158
+ latent_format = latent.SDXL
159
+ memory_usage_factor = 1.0
160
+
161
+ def process_clip_state_dict(self, state_dict):
162
+ replace_prefix = {"conditioner.embedders.0.model.": "clip_g."}
163
+ state_dict = utils.state_dict_prefix_replace(state_dict, replace_prefix, filter_keys=True)
164
+ return utils.clip_text_transformers_convert(state_dict, "clip_g.", "clip_g.transformer.")
165
+
166
+ def process_clip_state_dict_for_saving(self, state_dict):
167
+ state_dict_g = diffusers_convert.convert_text_enc_state_dict_v20(state_dict, "clip_g")
168
+ if "clip_g.transformer.text_model.embeddings.position_ids" in state_dict_g:
169
+ state_dict_g.pop("clip_g.transformer.text_model.embeddings.position_ids")
170
+ replace_prefix = {"clip_g": "conditioner.embedders.0.model"}
171
+ return utils.state_dict_prefix_replace(state_dict_g, replace_prefix)
172
+
173
+ def clip_target(self, state_dict: dict):
174
+ return {"clip_g": "text_encoder"}
175
+
176
+
177
+ class SDXL(BASE):
178
+ huggingface_repo = "stabilityai/stable-diffusion-xl-base-1.0"
179
+
180
+ unet_config = {
181
+ "model_channels": 320,
182
+ "use_linear_in_transformer": True,
183
+ "transformer_depth": [0, 0, 2, 2, 10, 10],
184
+ "context_dim": 2048,
185
+ "adm_in_channels": 2816,
186
+ "use_temporal_attention": False,
187
+ }
188
+
189
+ latent_format = latent.SDXL
190
+ memory_usage_factor = 0.8
191
+
192
+ def model_type(self, state_dict: dict):
193
+ if "v_pred" in state_dict:
194
+ return ModelType.V_PREDICTION
195
+ else:
196
+ return ModelType.EPS
197
+
198
+ def process_clip_state_dict(self, state_dict):
199
+ replace_prefix = {
200
+ "conditioner.embedders.0.transformer.text_model": "clip_l.transformer.text_model",
201
+ "conditioner.embedders.1.model.": "clip_g.",
202
+ }
203
+ state_dict = utils.state_dict_prefix_replace(state_dict, replace_prefix, filter_keys=True)
204
+ return utils.clip_text_transformers_convert(state_dict, "clip_g.", "clip_g.transformer.")
205
+
206
+ def process_clip_state_dict_for_saving(self, state_dict):
207
+ state_dict_g = diffusers_convert.convert_text_enc_state_dict_v20(state_dict, "clip_g")
208
+ for k in state_dict:
209
+ if k.startswith("clip_l"):
210
+ state_dict_g[k] = state_dict[k]
211
+
212
+ state_dict_g["clip_l.transformer.text_model.embeddings.position_ids"] = torch.arange(77).expand((1, -1))
213
+ pop_keys = ["clip_l.transformer.text_projection.weight", "clip_l.logit_scale"]
214
+ for p in pop_keys:
215
+ if p in state_dict_g:
216
+ state_dict_g.pop(p)
217
+
218
+ replace_prefix = {
219
+ "clip_g": "conditioner.embedders.1.model",
220
+ "clip_l": "conditioner.embedders.0",
221
+ }
222
+ return utils.state_dict_prefix_replace(state_dict_g, replace_prefix)
223
+
224
+ def clip_target(self, state_dict: dict):
225
+ return {"clip_l": "text_encoder", "clip_g": "text_encoder_2"}
226
+
227
+
228
+ class Flux(BASE):
229
+ huggingface_repo = "black-forest-labs/FLUX.1-dev"
230
+
231
+ unet_config = {
232
+ "image_model": "flux",
233
+ "guidance_embed": True,
234
+ }
235
+
236
+ sampling_settings = {}
237
+
238
+ unet_extra_config = {}
239
+ latent_format = latent.Flux
240
+
241
+ memory_usage_factor = 2.8
242
+
243
+ supported_inference_dtypes = [torch.bfloat16, torch.float16, torch.float32]
244
+
245
+ vae_key_prefix = ["vae."]
246
+ text_encoder_key_prefix = ["text_encoders."]
247
+
248
+ unet_target = "transformer"
249
+
250
+ def model_type(self, state_dict):
251
+ return ModelType.FLUX
252
+
253
+ def clip_target(self, state_dict: dict):
254
+ result = {}
255
+ pref = self.text_encoder_key_prefix[0]
256
+
257
+ if "{}clip_l.transformer.text_model.final_layer_norm.weight".format(pref) in state_dict:
258
+ result["clip_l"] = "text_encoder"
259
+
260
+ if "{}t5xxl.transformer.encoder.final_layer_norm.weight".format(pref) in state_dict:
261
+ result["t5xxl"] = "text_encoder_2"
262
+
263
+ elif "{}t5xxl.transformer.encoder.final_layer_norm.qweight".format(pref) in state_dict:
264
+ result["t5xxl"] = "text_encoder_2"
265
+
266
+ return result
267
+
268
+
269
+ class FluxSchnell(Flux):
270
+ huggingface_repo = "black-forest-labs/FLUX.1-schnell"
271
+
272
+ unet_config = {
273
+ "image_model": "flux",
274
+ "guidance_embed": False,
275
+ }
276
+
277
+ sampling_settings = {
278
+ "multiplier": 1.0,
279
+ "shift": 1.0,
280
+ }
281
+
282
+ supported_inference_dtypes = [torch.bfloat16, torch.float32]
283
+
284
+
285
+ class Chroma(FluxSchnell):
286
+ huggingface_repo = "Chroma"
287
+
288
+ unet_config = {
289
+ "image_model": "chroma",
290
+ }
291
+
292
+ sampling_settings = {
293
+ "multiplier": 1.0,
294
+ }
295
+
296
+ memory_usage_factor = 3.2
297
+
298
+ supported_inference_dtypes = [torch.bfloat16, torch.float16, torch.float32]
299
+
300
+ text_encoder_key_prefix = ["text_encoders.", "cond_stage_model."]
301
+
302
+ def clip_target(self, state_dict: dict):
303
+ for pref in self.text_encoder_key_prefix:
304
+ if "{}t5xxl.transformer.encoder.final_layer_norm.weight".format(pref) in state_dict:
305
+ return {"t5xxl": "text_encoder"}
306
+ elif "{}t5xxl.transformer.encoder.final_layer_norm.qweight".format(pref) in state_dict:
307
+ return {"t5xxl": "text_encoder"}
308
+
309
+ def process_vae_state_dict(self, state_dict):
310
+ replace_prefix = {"first_stage_model.": "vae."}
311
+ return utils.state_dict_prefix_replace(state_dict, replace_prefix)
312
+
313
+
314
+ class Lumina2(BASE):
315
+ huggingface_repo = "neta-art/Neta-Lumina"
316
+
317
+ unet_config = {
318
+ "image_model": "lumina2",
319
+ "dim": 2304,
320
+ }
321
+
322
+ sampling_settings = {
323
+ "multiplier": 1.0,
324
+ "shift": 6.0,
325
+ }
326
+
327
+ memory_usage_factor = 1.4
328
+
329
+ unet_extra_config = {}
330
+ latent_format = latent.Flux
331
+
332
+ supported_inference_dtypes = [torch.bfloat16, torch.float32]
333
+
334
+ vae_key_prefix = ["vae."]
335
+ text_encoder_key_prefix = ["text_encoders."]
336
+
337
+ unet_target = "transformer"
338
+
339
+ def model_type(self, state_dict):
340
+ return ModelType.FLOW
341
+
342
+ def clip_target(self, state_dict: dict):
343
+ pref = self.text_encoder_key_prefix[0]
344
+ if "{}gemma2_2b.transformer.model.embed_tokens.weight".format(pref) in state_dict:
345
+ state_dict.pop("{}gemma2_2b.logit_scale".format(pref), None)
346
+ state_dict.pop("{}spiece_model".format(pref), None)
347
+ return {"gemma2_2b.transformer": "text_encoder"}
348
+ else:
349
+ return {"gemma2_2b": "text_encoder"}
350
+
351
+
352
+ class ZImage(Lumina2):
353
+ huggingface_repo = "Tongyi-MAI/Z-Image-Turbo"
354
+
355
+ unet_config = {
356
+ "image_model": "lumina2",
357
+ "dim": 3840,
358
+ }
359
+
360
+ sampling_settings = {
361
+ "multiplier": 1.0,
362
+ "shift": 3.0,
363
+ }
364
+
365
+ memory_usage_factor = 2.0
366
+
367
+ supported_inference_dtypes = [torch.bfloat16, torch.float16, torch.float32]
368
+
369
+ def clip_target(self, state_dict={}):
370
+ return {"qwen3_4b.transformer": "text_encoder"}
371
+
372
+
373
+ class WAN21_T2V(BASE):
374
+ huggingface_repo = "Wan-AI/Wan2.1-T2V-14B"
375
+
376
+ unet_config = {
377
+ "image_model": "wan2.1",
378
+ "model_type": "t2v",
379
+ }
380
+
381
+ sampling_settings = {
382
+ "shift": 8.0,
383
+ }
384
+
385
+ unet_extra_config = {}
386
+ latent_format = latent.Wan21
387
+
388
+ memory_usage_factor = 1.0
389
+
390
+ supported_inference_dtypes = [torch.float16, torch.bfloat16, torch.float32]
391
+
392
+ vae_key_prefix = ["vae."]
393
+ text_encoder_key_prefix = ["text_encoders."]
394
+
395
+ unet_target = "transformer"
396
+
397
+ def __init__(self, unet_config):
398
+ super().__init__(unet_config)
399
+ self.memory_usage_factor = self.unet_config.get("dim", 2000) / 2000
400
+
401
+ def model_type(self, state_dict):
402
+ return ModelType.FLOW
403
+
404
+ def clip_target(self, state_dict: dict):
405
+ return {"umt5xxl": "text_encoder"}
406
+
407
+
408
+ class WAN21_I2V(WAN21_T2V):
409
+ huggingface_repo = "Wan-AI/Wan2.1-I2V-14B"
410
+
411
+ unet_config = {
412
+ "image_model": "wan2.1",
413
+ "model_type": "i2v",
414
+ "in_dim": 36,
415
+ }
416
+
417
+
418
+ class QwenImage(BASE):
419
+ huggingface_repo = "Qwen/Qwen-Image"
420
+
421
+ unet_config = {
422
+ "image_model": "qwen_image",
423
+ }
424
+
425
+ sampling_settings = {
426
+ "multiplier": 1.0,
427
+ "shift": 1.15,
428
+ }
429
+
430
+ memory_usage_factor = 1.8
431
+
432
+ unet_extra_config = {}
433
+ latent_format = latent.Wan21
434
+
435
+ supported_inference_dtypes = [torch.bfloat16, torch.float32]
436
+
437
+ vae_key_prefix = ["vae."]
438
+ text_encoder_key_prefix = ["text_encoders."]
439
+
440
+ unet_target = "transformer"
441
+
442
+ def model_type(self, state_dict):
443
+ return ModelType.FLOW
444
+
445
+ def clip_target(self, state_dict: dict):
446
+ pref = self.text_encoder_key_prefix[0]
447
+ if "{}.qwen25_7b.transformer.model.embed_tokens.weight".format(pref) in state_dict:
448
+ state_dict.pop("{}qwen25_7b.logit_scale".format(pref), None)
449
+ return {"qwen25_7b.transformer": "text_encoder"}
450
+ else:
451
+ return {"qwen25_7b": "text_encoder"}
452
+
453
+
454
+ models = [
455
+ SD15,
456
+ SDXL,
457
+ SDXLRefiner,
458
+ Flux,
459
+ FluxSchnell,
460
+ Chroma,
461
+ Lumina2,
462
+ ZImage,
463
+ WAN21_T2V,
464
+ WAN21_I2V,
465
+ QwenImage,
466
+ ]
modules_forge/packages/huggingface_guess/utils.py ADDED
@@ -0,0 +1,482 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # reference: https://github.com/comfyanonymous/ComfyUI/blob/v0.3.52/comfy/utils.py
2
+
3
+ import math
4
+ import struct
5
+
6
+ import torch
7
+
8
+
9
+ def calculate_parameters(sd, prefix=""):
10
+ params = 0
11
+ for k in sd.keys():
12
+ if k.startswith(prefix):
13
+ w = sd[k]
14
+ params += w.nelement()
15
+ return params
16
+
17
+
18
+ def weight_dtype(sd, prefix=""):
19
+ dtypes = {}
20
+ for k in sd.keys():
21
+ if k.startswith(prefix):
22
+ w = sd[k]
23
+ dtypes[w.dtype] = dtypes.get(w.dtype, 0) + w.numel()
24
+
25
+ if len(dtypes) == 0:
26
+ return None
27
+
28
+ return max(dtypes, key=dtypes.get)
29
+
30
+
31
+ def state_dict_key_replace(state_dict, keys_to_replace):
32
+ for x in keys_to_replace:
33
+ if x in state_dict:
34
+ state_dict[keys_to_replace[x]] = state_dict.pop(x)
35
+ return state_dict
36
+
37
+
38
+ def state_dict_prefix_replace(state_dict, replace_prefix, filter_keys=False):
39
+ if filter_keys:
40
+ out = {}
41
+ else:
42
+ out = state_dict
43
+ for rp in replace_prefix:
44
+ replace = list(map(lambda a: (a, "{}{}".format(replace_prefix[rp], a[len(rp) :])), filter(lambda a: a.startswith(rp), state_dict.keys())))
45
+ for x in replace:
46
+ w = state_dict.pop(x[0])
47
+ out[x[1]] = w
48
+ return out
49
+
50
+
51
+ def transformers_convert(sd, prefix_from, prefix_to, number):
52
+ keys_to_replace = {
53
+ "{}positional_embedding": "{}embeddings.position_embedding.weight",
54
+ "{}token_embedding.weight": "{}embeddings.token_embedding.weight",
55
+ "{}ln_final.weight": "{}final_layer_norm.weight",
56
+ "{}ln_final.bias": "{}final_layer_norm.bias",
57
+ }
58
+
59
+ for k in keys_to_replace:
60
+ x = k.format(prefix_from)
61
+ if x in sd:
62
+ sd[keys_to_replace[k].format(prefix_to)] = sd.pop(x)
63
+
64
+ resblock_to_replace = {
65
+ "ln_1": "layer_norm1",
66
+ "ln_2": "layer_norm2",
67
+ "mlp.c_fc": "mlp.fc1",
68
+ "mlp.c_proj": "mlp.fc2",
69
+ "attn.out_proj": "self_attn.out_proj",
70
+ }
71
+
72
+ for resblock in range(number):
73
+ for x in resblock_to_replace:
74
+ for y in ["weight", "bias"]:
75
+ k = "{}transformer.resblocks.{}.{}.{}".format(prefix_from, resblock, x, y)
76
+ k_to = "{}encoder.layers.{}.{}.{}".format(prefix_to, resblock, resblock_to_replace[x], y)
77
+ if k in sd:
78
+ sd[k_to] = sd.pop(k)
79
+
80
+ for y in ["weight", "bias"]:
81
+ k_from = "{}transformer.resblocks.{}.attn.in_proj_{}".format(prefix_from, resblock, y)
82
+ if k_from in sd:
83
+ weights = sd.pop(k_from)
84
+ shape_from = weights.shape[0] // 3
85
+ for x in range(3):
86
+ p = ["self_attn.q_proj", "self_attn.k_proj", "self_attn.v_proj"]
87
+ k_to = "{}encoder.layers.{}.{}.{}".format(prefix_to, resblock, p[x], y)
88
+ sd[k_to] = weights[shape_from * x : shape_from * (x + 1)]
89
+
90
+ return sd
91
+
92
+
93
+ def clip_text_transformers_convert(sd, prefix_from, prefix_to):
94
+ sd = transformers_convert(sd, prefix_from, "{}text_model.".format(prefix_to), 32)
95
+
96
+ tp = "{}text_projection.weight".format(prefix_from)
97
+ if tp in sd:
98
+ sd["{}text_projection.weight".format(prefix_to)] = sd.pop(tp)
99
+
100
+ tp = "{}text_projection".format(prefix_from)
101
+ if tp in sd:
102
+ sd["{}text_projection.weight".format(prefix_to)] = sd.pop(tp).transpose(0, 1).contiguous()
103
+ return sd
104
+
105
+
106
+ UNET_MAP_ATTENTIONS = {
107
+ "proj_in.weight",
108
+ "proj_in.bias",
109
+ "proj_out.weight",
110
+ "proj_out.bias",
111
+ "norm.weight",
112
+ "norm.bias",
113
+ }
114
+
115
+ TRANSFORMER_BLOCKS = {
116
+ "norm1.weight",
117
+ "norm1.bias",
118
+ "norm2.weight",
119
+ "norm2.bias",
120
+ "norm3.weight",
121
+ "norm3.bias",
122
+ "attn1.to_q.weight",
123
+ "attn1.to_k.weight",
124
+ "attn1.to_v.weight",
125
+ "attn1.to_out.0.weight",
126
+ "attn1.to_out.0.bias",
127
+ "attn2.to_q.weight",
128
+ "attn2.to_k.weight",
129
+ "attn2.to_v.weight",
130
+ "attn2.to_out.0.weight",
131
+ "attn2.to_out.0.bias",
132
+ "ff.net.0.proj.weight",
133
+ "ff.net.0.proj.bias",
134
+ "ff.net.2.weight",
135
+ "ff.net.2.bias",
136
+ }
137
+
138
+ UNET_MAP_RESNET = {
139
+ "in_layers.2.weight": "conv1.weight",
140
+ "in_layers.2.bias": "conv1.bias",
141
+ "emb_layers.1.weight": "time_emb_proj.weight",
142
+ "emb_layers.1.bias": "time_emb_proj.bias",
143
+ "out_layers.3.weight": "conv2.weight",
144
+ "out_layers.3.bias": "conv2.bias",
145
+ "skip_connection.weight": "conv_shortcut.weight",
146
+ "skip_connection.bias": "conv_shortcut.bias",
147
+ "in_layers.0.weight": "norm1.weight",
148
+ "in_layers.0.bias": "norm1.bias",
149
+ "out_layers.0.weight": "norm2.weight",
150
+ "out_layers.0.bias": "norm2.bias",
151
+ }
152
+
153
+ UNET_MAP_BASIC = {
154
+ ("label_emb.0.0.weight", "class_embedding.linear_1.weight"),
155
+ ("label_emb.0.0.bias", "class_embedding.linear_1.bias"),
156
+ ("label_emb.0.2.weight", "class_embedding.linear_2.weight"),
157
+ ("label_emb.0.2.bias", "class_embedding.linear_2.bias"),
158
+ ("label_emb.0.0.weight", "add_embedding.linear_1.weight"),
159
+ ("label_emb.0.0.bias", "add_embedding.linear_1.bias"),
160
+ ("label_emb.0.2.weight", "add_embedding.linear_2.weight"),
161
+ ("label_emb.0.2.bias", "add_embedding.linear_2.bias"),
162
+ ("input_blocks.0.0.weight", "conv_in.weight"),
163
+ ("input_blocks.0.0.bias", "conv_in.bias"),
164
+ ("out.0.weight", "conv_norm_out.weight"),
165
+ ("out.0.bias", "conv_norm_out.bias"),
166
+ ("out.2.weight", "conv_out.weight"),
167
+ ("out.2.bias", "conv_out.bias"),
168
+ ("time_embed.0.weight", "time_embedding.linear_1.weight"),
169
+ ("time_embed.0.bias", "time_embedding.linear_1.bias"),
170
+ ("time_embed.2.weight", "time_embedding.linear_2.weight"),
171
+ ("time_embed.2.bias", "time_embedding.linear_2.bias"),
172
+ }
173
+
174
+
175
+ def unet_to_diffusers(unet_config):
176
+ if "num_res_blocks" not in unet_config:
177
+ return {}
178
+ num_res_blocks = unet_config["num_res_blocks"]
179
+ channel_mult = unet_config["channel_mult"]
180
+ transformer_depth = unet_config["transformer_depth"][:]
181
+ transformer_depth_output = unet_config["transformer_depth_output"][:]
182
+ num_blocks = len(channel_mult)
183
+
184
+ transformers_mid = unet_config.get("transformer_depth_middle", None)
185
+
186
+ diffusers_unet_map = {}
187
+ for x in range(num_blocks):
188
+ n = 1 + (num_res_blocks[x] + 1) * x
189
+ for i in range(num_res_blocks[x]):
190
+ for b in UNET_MAP_RESNET:
191
+ diffusers_unet_map["down_blocks.{}.resnets.{}.{}".format(x, i, UNET_MAP_RESNET[b])] = "input_blocks.{}.0.{}".format(n, b)
192
+ num_transformers = transformer_depth.pop(0)
193
+ if num_transformers > 0:
194
+ for b in UNET_MAP_ATTENTIONS:
195
+ diffusers_unet_map["down_blocks.{}.attentions.{}.{}".format(x, i, b)] = "input_blocks.{}.1.{}".format(n, b)
196
+ for t in range(num_transformers):
197
+ for b in TRANSFORMER_BLOCKS:
198
+ diffusers_unet_map["down_blocks.{}.attentions.{}.transformer_blocks.{}.{}".format(x, i, t, b)] = "input_blocks.{}.1.transformer_blocks.{}.{}".format(n, t, b)
199
+ n += 1
200
+ for k in ["weight", "bias"]:
201
+ diffusers_unet_map["down_blocks.{}.downsamplers.0.conv.{}".format(x, k)] = "input_blocks.{}.0.op.{}".format(n, k)
202
+
203
+ i = 0
204
+ for b in UNET_MAP_ATTENTIONS:
205
+ diffusers_unet_map["mid_block.attentions.{}.{}".format(i, b)] = "middle_block.1.{}".format(b)
206
+ for t in range(transformers_mid):
207
+ for b in TRANSFORMER_BLOCKS:
208
+ diffusers_unet_map["mid_block.attentions.{}.transformer_blocks.{}.{}".format(i, t, b)] = "middle_block.1.transformer_blocks.{}.{}".format(t, b)
209
+
210
+ for i, n in enumerate([0, 2]):
211
+ for b in UNET_MAP_RESNET:
212
+ diffusers_unet_map["mid_block.resnets.{}.{}".format(i, UNET_MAP_RESNET[b])] = "middle_block.{}.{}".format(n, b)
213
+
214
+ num_res_blocks = list(reversed(num_res_blocks))
215
+ for x in range(num_blocks):
216
+ n = (num_res_blocks[x] + 1) * x
217
+ l = num_res_blocks[x] + 1
218
+ for i in range(l):
219
+ c = 0
220
+ for b in UNET_MAP_RESNET:
221
+ diffusers_unet_map["up_blocks.{}.resnets.{}.{}".format(x, i, UNET_MAP_RESNET[b])] = "output_blocks.{}.0.{}".format(n, b)
222
+ c += 1
223
+ num_transformers = transformer_depth_output.pop()
224
+ if num_transformers > 0:
225
+ c += 1
226
+ for b in UNET_MAP_ATTENTIONS:
227
+ diffusers_unet_map["up_blocks.{}.attentions.{}.{}".format(x, i, b)] = "output_blocks.{}.1.{}".format(n, b)
228
+ for t in range(num_transformers):
229
+ for b in TRANSFORMER_BLOCKS:
230
+ diffusers_unet_map["up_blocks.{}.attentions.{}.transformer_blocks.{}.{}".format(x, i, t, b)] = "output_blocks.{}.1.transformer_blocks.{}.{}".format(n, t, b)
231
+ if i == l - 1:
232
+ for k in ["weight", "bias"]:
233
+ diffusers_unet_map["up_blocks.{}.upsamplers.0.conv.{}".format(x, k)] = "output_blocks.{}.{}.conv.{}".format(n, c, k)
234
+ n += 1
235
+
236
+ for k in UNET_MAP_BASIC:
237
+ diffusers_unet_map[k[1]] = k[0]
238
+
239
+ return diffusers_unet_map
240
+
241
+
242
+ def swap_scale_shift(weight):
243
+ shift, scale = weight.chunk(2, dim=0)
244
+ new_weight = torch.cat([scale, shift], dim=0)
245
+ return new_weight
246
+
247
+
248
+ MMDIT_MAP_BASIC = {
249
+ ("context_embedder.bias", "context_embedder.bias"),
250
+ ("context_embedder.weight", "context_embedder.weight"),
251
+ ("t_embedder.mlp.0.bias", "time_text_embed.timestep_embedder.linear_1.bias"),
252
+ ("t_embedder.mlp.0.weight", "time_text_embed.timestep_embedder.linear_1.weight"),
253
+ ("t_embedder.mlp.2.bias", "time_text_embed.timestep_embedder.linear_2.bias"),
254
+ ("t_embedder.mlp.2.weight", "time_text_embed.timestep_embedder.linear_2.weight"),
255
+ ("x_embedder.proj.bias", "pos_embed.proj.bias"),
256
+ ("x_embedder.proj.weight", "pos_embed.proj.weight"),
257
+ ("y_embedder.mlp.0.bias", "time_text_embed.text_embedder.linear_1.bias"),
258
+ ("y_embedder.mlp.0.weight", "time_text_embed.text_embedder.linear_1.weight"),
259
+ ("y_embedder.mlp.2.bias", "time_text_embed.text_embedder.linear_2.bias"),
260
+ ("y_embedder.mlp.2.weight", "time_text_embed.text_embedder.linear_2.weight"),
261
+ ("pos_embed", "pos_embed.pos_embed"),
262
+ ("final_layer.adaLN_modulation.1.bias", "norm_out.linear.bias", swap_scale_shift),
263
+ ("final_layer.adaLN_modulation.1.weight", "norm_out.linear.weight", swap_scale_shift),
264
+ ("final_layer.linear.bias", "proj_out.bias"),
265
+ ("final_layer.linear.weight", "proj_out.weight"),
266
+ }
267
+
268
+ MMDIT_MAP_BLOCK = {
269
+ ("context_block.adaLN_modulation.1.bias", "norm1_context.linear.bias"),
270
+ ("context_block.adaLN_modulation.1.weight", "norm1_context.linear.weight"),
271
+ ("context_block.attn.proj.bias", "attn.to_add_out.bias"),
272
+ ("context_block.attn.proj.weight", "attn.to_add_out.weight"),
273
+ ("context_block.mlp.fc1.bias", "ff_context.net.0.proj.bias"),
274
+ ("context_block.mlp.fc1.weight", "ff_context.net.0.proj.weight"),
275
+ ("context_block.mlp.fc2.bias", "ff_context.net.2.bias"),
276
+ ("context_block.mlp.fc2.weight", "ff_context.net.2.weight"),
277
+ ("context_block.attn.ln_q.weight", "attn.norm_added_q.weight"),
278
+ ("context_block.attn.ln_k.weight", "attn.norm_added_k.weight"),
279
+ ("x_block.adaLN_modulation.1.bias", "norm1.linear.bias"),
280
+ ("x_block.adaLN_modulation.1.weight", "norm1.linear.weight"),
281
+ ("x_block.attn.proj.bias", "attn.to_out.0.bias"),
282
+ ("x_block.attn.proj.weight", "attn.to_out.0.weight"),
283
+ ("x_block.attn.ln_q.weight", "attn.norm_q.weight"),
284
+ ("x_block.attn.ln_k.weight", "attn.norm_k.weight"),
285
+ ("x_block.attn2.proj.bias", "attn2.to_out.0.bias"),
286
+ ("x_block.attn2.proj.weight", "attn2.to_out.0.weight"),
287
+ ("x_block.attn2.ln_q.weight", "attn2.norm_q.weight"),
288
+ ("x_block.attn2.ln_k.weight", "attn2.norm_k.weight"),
289
+ ("x_block.mlp.fc1.bias", "ff.net.0.proj.bias"),
290
+ ("x_block.mlp.fc1.weight", "ff.net.0.proj.weight"),
291
+ ("x_block.mlp.fc2.bias", "ff.net.2.bias"),
292
+ ("x_block.mlp.fc2.weight", "ff.net.2.weight"),
293
+ }
294
+
295
+
296
+ def mmdit_to_diffusers(mmdit_config, output_prefix=""):
297
+ key_map = {}
298
+
299
+ depth = mmdit_config.get("depth", 0)
300
+ num_blocks = mmdit_config.get("num_blocks", depth)
301
+ for i in range(num_blocks):
302
+ block_from = "transformer_blocks.{}".format(i)
303
+ block_to = "{}joint_blocks.{}".format(output_prefix, i)
304
+
305
+ offset = depth * 64
306
+
307
+ for end in ("weight", "bias"):
308
+ k = "{}.attn.".format(block_from)
309
+ qkv = "{}.x_block.attn.qkv.{}".format(block_to, end)
310
+ key_map["{}to_q.{}".format(k, end)] = (qkv, (0, 0, offset))
311
+ key_map["{}to_k.{}".format(k, end)] = (qkv, (0, offset, offset))
312
+ key_map["{}to_v.{}".format(k, end)] = (qkv, (0, offset * 2, offset))
313
+
314
+ qkv = "{}.context_block.attn.qkv.{}".format(block_to, end)
315
+ key_map["{}add_q_proj.{}".format(k, end)] = (qkv, (0, 0, offset))
316
+ key_map["{}add_k_proj.{}".format(k, end)] = (qkv, (0, offset, offset))
317
+ key_map["{}add_v_proj.{}".format(k, end)] = (qkv, (0, offset * 2, offset))
318
+
319
+ k = "{}.attn2.".format(block_from)
320
+ qkv = "{}.x_block.attn2.qkv.{}".format(block_to, end)
321
+ key_map["{}to_q.{}".format(k, end)] = (qkv, (0, 0, offset))
322
+ key_map["{}to_k.{}".format(k, end)] = (qkv, (0, offset, offset))
323
+ key_map["{}to_v.{}".format(k, end)] = (qkv, (0, offset * 2, offset))
324
+
325
+ for k in MMDIT_MAP_BLOCK:
326
+ key_map["{}.{}".format(block_from, k[1])] = "{}.{}".format(block_to, k[0])
327
+
328
+ map_basic = MMDIT_MAP_BASIC.copy()
329
+ map_basic.add(("joint_blocks.{}.context_block.adaLN_modulation.1.bias".format(depth - 1), "transformer_blocks.{}.norm1_context.linear.bias".format(depth - 1), swap_scale_shift))
330
+ map_basic.add(("joint_blocks.{}.context_block.adaLN_modulation.1.weight".format(depth - 1), "transformer_blocks.{}.norm1_context.linear.weight".format(depth - 1), swap_scale_shift))
331
+
332
+ for k in map_basic:
333
+ if len(k) > 2:
334
+ key_map[k[1]] = ("{}{}".format(output_prefix, k[0]), None, k[2])
335
+ else:
336
+ key_map[k[1]] = "{}{}".format(output_prefix, k[0])
337
+
338
+ return key_map
339
+
340
+
341
+ def auraflow_to_diffusers(mmdit_config, output_prefix=""):
342
+ n_double_layers = mmdit_config.get("n_double_layers", 0)
343
+ n_layers = mmdit_config.get("n_layers", 0)
344
+
345
+ key_map = {}
346
+ for i in range(n_layers):
347
+ if i < n_double_layers:
348
+ index = i
349
+ prefix_from = "joint_transformer_blocks"
350
+ prefix_to = "{}double_layers".format(output_prefix)
351
+ block_map = {
352
+ "attn.to_q.weight": "attn.w2q.weight",
353
+ "attn.to_k.weight": "attn.w2k.weight",
354
+ "attn.to_v.weight": "attn.w2v.weight",
355
+ "attn.to_out.0.weight": "attn.w2o.weight",
356
+ "attn.add_q_proj.weight": "attn.w1q.weight",
357
+ "attn.add_k_proj.weight": "attn.w1k.weight",
358
+ "attn.add_v_proj.weight": "attn.w1v.weight",
359
+ "attn.to_add_out.weight": "attn.w1o.weight",
360
+ "ff.linear_1.weight": "mlpX.c_fc1.weight",
361
+ "ff.linear_2.weight": "mlpX.c_fc2.weight",
362
+ "ff.out_projection.weight": "mlpX.c_proj.weight",
363
+ "ff_context.linear_1.weight": "mlpC.c_fc1.weight",
364
+ "ff_context.linear_2.weight": "mlpC.c_fc2.weight",
365
+ "ff_context.out_projection.weight": "mlpC.c_proj.weight",
366
+ "norm1.linear.weight": "modX.1.weight",
367
+ "norm1_context.linear.weight": "modC.1.weight",
368
+ }
369
+ else:
370
+ index = i - n_double_layers
371
+ prefix_from = "single_transformer_blocks"
372
+ prefix_to = "{}single_layers".format(output_prefix)
373
+
374
+ block_map = {
375
+ "attn.to_q.weight": "attn.w1q.weight",
376
+ "attn.to_k.weight": "attn.w1k.weight",
377
+ "attn.to_v.weight": "attn.w1v.weight",
378
+ "attn.to_out.0.weight": "attn.w1o.weight",
379
+ "norm1.linear.weight": "modCX.1.weight",
380
+ "ff.linear_1.weight": "mlp.c_fc1.weight",
381
+ "ff.linear_2.weight": "mlp.c_fc2.weight",
382
+ "ff.out_projection.weight": "mlp.c_proj.weight",
383
+ }
384
+
385
+ for k in block_map:
386
+ key_map["{}.{}.{}".format(prefix_from, index, k)] = "{}.{}.{}".format(prefix_to, index, block_map[k])
387
+
388
+ MAP_BASIC = {
389
+ ("positional_encoding", "pos_embed.pos_embed"),
390
+ ("register_tokens", "register_tokens"),
391
+ ("t_embedder.mlp.0.weight", "time_step_proj.linear_1.weight"),
392
+ ("t_embedder.mlp.0.bias", "time_step_proj.linear_1.bias"),
393
+ ("t_embedder.mlp.2.weight", "time_step_proj.linear_2.weight"),
394
+ ("t_embedder.mlp.2.bias", "time_step_proj.linear_2.bias"),
395
+ ("cond_seq_linear.weight", "context_embedder.weight"),
396
+ ("init_x_linear.weight", "pos_embed.proj.weight"),
397
+ ("init_x_linear.bias", "pos_embed.proj.bias"),
398
+ ("final_linear.weight", "proj_out.weight"),
399
+ ("modF.1.weight", "norm_out.linear.weight", swap_scale_shift),
400
+ }
401
+
402
+ for k in MAP_BASIC:
403
+ if len(k) > 2:
404
+ key_map[k[1]] = ("{}{}".format(output_prefix, k[0]), None, k[2])
405
+ else:
406
+ key_map[k[1]] = "{}{}".format(output_prefix, k[0])
407
+
408
+ return key_map
409
+
410
+
411
+ def repeat_to_batch_size(tensor, batch_size, dim=0):
412
+ if tensor.shape[dim] > batch_size:
413
+ return tensor.narrow(dim, 0, batch_size)
414
+ elif tensor.shape[dim] < batch_size:
415
+ return tensor.repeat(dim * [1] + [math.ceil(batch_size / tensor.shape[dim])] + [1] * (len(tensor.shape) - 1 - dim)).narrow(dim, 0, batch_size)
416
+ return tensor
417
+
418
+
419
+ def resize_to_batch_size(tensor, batch_size):
420
+ in_batch_size = tensor.shape[0]
421
+ if in_batch_size == batch_size:
422
+ return tensor
423
+
424
+ if batch_size <= 1:
425
+ return tensor[:batch_size]
426
+
427
+ output = torch.empty([batch_size] + list(tensor.shape)[1:], dtype=tensor.dtype, device=tensor.device)
428
+ if batch_size < in_batch_size:
429
+ scale = (in_batch_size - 1) / (batch_size - 1)
430
+ for i in range(batch_size):
431
+ output[i] = tensor[min(round(i * scale), in_batch_size - 1)]
432
+ else:
433
+ scale = in_batch_size / batch_size
434
+ for i in range(batch_size):
435
+ output[i] = tensor[min(math.floor((i + 0.5) * scale), in_batch_size - 1)]
436
+
437
+ return output
438
+
439
+
440
+ def convert_sd_to(state_dict, dtype):
441
+ keys = list(state_dict.keys())
442
+ for k in keys:
443
+ state_dict[k] = state_dict[k].to(dtype)
444
+ return state_dict
445
+
446
+
447
+ def safetensors_header(safetensors_path, max_size=100 * 1024 * 1024):
448
+ with open(safetensors_path, "rb") as f:
449
+ header = f.read(8)
450
+ length_of_header = struct.unpack("<Q", header)[0]
451
+ if length_of_header > max_size:
452
+ return None
453
+ return f.read(length_of_header)
454
+
455
+
456
+ def set_attr(obj, attr, value):
457
+ attrs = attr.split(".")
458
+ for name in attrs[:-1]:
459
+ obj = getattr(obj, name)
460
+ prev = getattr(obj, attrs[-1])
461
+ setattr(obj, attrs[-1], value)
462
+ return prev
463
+
464
+
465
+ def set_attr_param(obj, attr, value):
466
+ return set_attr(obj, attr, torch.nn.Parameter(value, requires_grad=False))
467
+
468
+
469
+ def copy_to_param(obj, attr, value):
470
+ # inplace update tensor instead of replacing it
471
+ attrs = attr.split(".")
472
+ for name in attrs[:-1]:
473
+ obj = getattr(obj, name)
474
+ prev = getattr(obj, attrs[-1])
475
+ prev.data.copy_(value)
476
+
477
+
478
+ def get_attr(obj, attr: str):
479
+ attrs = attr.split(".")
480
+ for name in attrs:
481
+ obj = getattr(obj, name)
482
+ return obj
modules_forge/packages/k_diffusion/deis.py ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Reimplementation of DEIS (https://github.com/qsh-zh/deis)
3
+ Credit: https://github.com/zju-pi/diff-sampler/blob/main/gits-main/solver_utils.py
4
+ License: Apache-2.0
5
+ """
6
+
7
+ import numpy as np
8
+ import torch
9
+
10
+ # ----------------------------------------------------------------------------
11
+
12
+
13
+ def edm2t(edm_steps, epsilon_s=1e-3, sigma_min=0.002, sigma_max=80):
14
+ vp_sigma = lambda beta_d, beta_min: lambda t: (np.e ** (0.5 * beta_d * (t**2) + beta_min * t) - 1) ** 0.5
15
+ vp_sigma_inv = lambda beta_d, beta_min: lambda sigma: ((beta_min**2 + 2 * beta_d * (sigma**2 + 1).log()).sqrt() - beta_min) / beta_d
16
+ vp_beta_d = 2 * (np.log(torch.tensor(sigma_min).cpu() ** 2 + 1) / epsilon_s - np.log(torch.tensor(sigma_max).cpu() ** 2 + 1)) / (epsilon_s - 1)
17
+ vp_beta_min = np.log(torch.tensor(sigma_max).cpu() ** 2 + 1) - 0.5 * vp_beta_d
18
+ t_steps = vp_sigma_inv(vp_beta_d.clone().detach().cpu(), vp_beta_min.clone().detach().cpu())(edm_steps.clone().detach().cpu())
19
+ return t_steps, vp_beta_min, vp_beta_d + vp_beta_min
20
+
21
+
22
+ # ----------------------------------------------------------------------------
23
+
24
+
25
+ def cal_poly(prev_t, j, taus):
26
+ poly = 1
27
+ for k in range(prev_t.shape[0]):
28
+ if k == j:
29
+ continue
30
+ poly *= (taus - prev_t[k]) / (prev_t[j] - prev_t[k])
31
+ return poly
32
+
33
+
34
+ # ----------------------------------------------------------------------------
35
+
36
+
37
+ def t2alpha_fn(beta_0, beta_1, t):
38
+ return torch.exp(-0.5 * t**2 * (beta_1 - beta_0) - t * beta_0)
39
+
40
+
41
+ # ----------------------------------------------------------------------------
42
+
43
+
44
+ def cal_intergrand(beta_0, beta_1, taus):
45
+ with torch.inference_mode(mode=False):
46
+ taus = taus.clone()
47
+ beta_0 = beta_0.clone()
48
+ beta_1 = beta_1.clone()
49
+ with torch.enable_grad():
50
+ taus.requires_grad_(True)
51
+ alpha = t2alpha_fn(beta_0, beta_1, taus)
52
+ log_alpha = alpha.log()
53
+ log_alpha.sum().backward()
54
+ d_log_alpha_dtau = taus.grad
55
+ integrand = -0.5 * d_log_alpha_dtau / torch.sqrt(alpha * (1 - alpha))
56
+ return integrand
57
+
58
+
59
+ # ----------------------------------------------------------------------------
60
+
61
+
62
+ def get_deis_coeff_list(t_steps, max_order, N=10000, deis_mode="tab"):
63
+ """
64
+ Get the coefficient list for DEIS sampling.
65
+
66
+ Args:
67
+ t_steps: A pytorch tensor. The time steps for sampling.
68
+ max_order: A `int`. Maximum order of the solver. 1 <= max_order <= 4
69
+ N: A `int`. Use how many points to perform the numerical integration when deis_mode=='tab'.
70
+ deis_mode: A `str`. Select between 'tab' and 'rhoab'. Type of DEIS.
71
+ Returns:
72
+ A pytorch tensor. A batch of generated samples or sampling trajectories if return_inters=True.
73
+ """
74
+ if deis_mode == "tab":
75
+ t_steps, beta_0, beta_1 = edm2t(t_steps)
76
+ C = []
77
+ for i, (t_cur, t_next) in enumerate(zip(t_steps[:-1], t_steps[1:])):
78
+ order = min(i + 1, max_order)
79
+ if order == 1:
80
+ C.append([])
81
+ else:
82
+ taus = torch.linspace(t_cur, t_next, N) # split the interval for integral appximation
83
+ dtau = (t_next - t_cur) / N
84
+ prev_t = t_steps[[i - k for k in range(order)]]
85
+ coeff_temp = []
86
+ integrand = cal_intergrand(beta_0, beta_1, taus)
87
+ for j in range(order):
88
+ poly = cal_poly(prev_t, j, taus)
89
+ coeff_temp.append(torch.sum(integrand * poly) * dtau)
90
+ C.append(coeff_temp)
91
+
92
+ elif deis_mode == "rhoab":
93
+ # Analytical solution, second order
94
+ def get_def_intergral_2(a, b, start, end, c):
95
+ coeff = (end**3 - start**3) / 3 - (end**2 - start**2) * (a + b) / 2 + (end - start) * a * b
96
+ return coeff / ((c - a) * (c - b))
97
+
98
+ # Analytical solution, third order
99
+ def get_def_intergral_3(a, b, c, start, end, d):
100
+ coeff = (end**4 - start**4) / 4 - (end**3 - start**3) * (a + b + c) / 3 + (end**2 - start**2) * (a * b + a * c + b * c) / 2 - (end - start) * a * b * c
101
+ return coeff / ((d - a) * (d - b) * (d - c))
102
+
103
+ C = []
104
+ for i, (t_cur, t_next) in enumerate(zip(t_steps[:-1], t_steps[1:])):
105
+ order = min(i, max_order)
106
+ if order == 0:
107
+ C.append([])
108
+ else:
109
+ prev_t = t_steps[[i - k for k in range(order + 1)]]
110
+ if order == 1:
111
+ coeff_cur = ((t_next - prev_t[1]) ** 2 - (t_cur - prev_t[1]) ** 2) / (2 * (t_cur - prev_t[1]))
112
+ coeff_prev1 = (t_next - t_cur) ** 2 / (2 * (prev_t[1] - t_cur))
113
+ coeff_temp = [coeff_cur, coeff_prev1]
114
+ elif order == 2:
115
+ coeff_cur = get_def_intergral_2(prev_t[1], prev_t[2], t_cur, t_next, t_cur)
116
+ coeff_prev1 = get_def_intergral_2(t_cur, prev_t[2], t_cur, t_next, prev_t[1])
117
+ coeff_prev2 = get_def_intergral_2(t_cur, prev_t[1], t_cur, t_next, prev_t[2])
118
+ coeff_temp = [coeff_cur, coeff_prev1, coeff_prev2]
119
+ elif order == 3:
120
+ coeff_cur = get_def_intergral_3(prev_t[1], prev_t[2], prev_t[3], t_cur, t_next, t_cur)
121
+ coeff_prev1 = get_def_intergral_3(t_cur, prev_t[2], prev_t[3], t_cur, t_next, prev_t[1])
122
+ coeff_prev2 = get_def_intergral_3(t_cur, prev_t[1], prev_t[3], t_cur, t_next, prev_t[2])
123
+ coeff_prev3 = get_def_intergral_3(t_cur, prev_t[1], prev_t[2], t_cur, t_next, prev_t[3])
124
+ coeff_temp = [coeff_cur, coeff_prev1, coeff_prev2, coeff_prev3]
125
+ C.append(coeff_temp)
126
+
127
+ return C
modules_forge/packages/k_diffusion/external.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from torch import nn
3
+
4
+ from . import sampling
5
+
6
+
7
+ class ForgeScheduleLinker(nn.Module):
8
+ def __init__(self, predictor):
9
+ super().__init__()
10
+ self.predictor = predictor
11
+
12
+ @property
13
+ def sigmas(self):
14
+ return self.predictor.sigmas
15
+
16
+ @property
17
+ def log_sigmas(self):
18
+ return self.predictor.sigmas.log()
19
+
20
+ @property
21
+ def sigma_min(self):
22
+ return self.predictor.sigma_min()
23
+
24
+ @property
25
+ def sigma_max(self):
26
+ return self.predictor.sigma_max()
27
+
28
+ def get_sigmas(self, n=None):
29
+ if n is None:
30
+ return sampling.append_zero(self.sigmas.flip(0))
31
+ t_max = len(self.sigmas) - 1
32
+ t = torch.linspace(t_max, 0, n, device=self.sigmas.device)
33
+ return sampling.append_zero(self.t_to_sigma(t))
34
+
35
+ def sigma_to_t(self, sigma, quantize=None):
36
+ return self.predictor.timestep(sigma)
37
+
38
+ def t_to_sigma(self, t):
39
+ return self.predictor.sigma(t)
modules_forge/packages/k_diffusion/sampling.py ADDED
@@ -0,0 +1,845 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # https://github.com/comfyanonymous/ComfyUI/blob/v0.3.75/comfy/k_diffusion/sampling.py
2
+
3
+ import math
4
+ from functools import partial
5
+
6
+ import torch
7
+ import torchsde
8
+ from scipy import integrate
9
+ from tqdm.auto import trange
10
+
11
+ from backend.patcher.base import set_model_options_post_cfg_function
12
+
13
+ from . import utils
14
+
15
+
16
+ def _is_const(sampling) -> bool:
17
+ return sampling.prediction_type == "const"
18
+
19
+
20
+ def append_zero(x):
21
+ return torch.cat([x, x.new_zeros([1])])
22
+
23
+
24
+ def get_sigmas_karras(n, sigma_min, sigma_max, rho=7.0, device="cpu"):
25
+ """Constructs the noise schedule of Karras et al. (2022)"""
26
+ ramp = torch.linspace(0, 1, n, device=device)
27
+ min_inv_rho = sigma_min ** (1 / rho)
28
+ max_inv_rho = sigma_max ** (1 / rho)
29
+ sigmas = (max_inv_rho + ramp * (min_inv_rho - max_inv_rho)) ** rho
30
+ return append_zero(sigmas).to(device)
31
+
32
+
33
+ def get_sigmas_exponential(n, sigma_min, sigma_max, device="cpu"):
34
+ """Constructs an exponential noise schedule"""
35
+ sigmas = torch.linspace(math.log(sigma_max), math.log(sigma_min), n, device=device).exp()
36
+ return append_zero(sigmas)
37
+
38
+
39
+ def get_sigmas_polyexponential(n, sigma_min, sigma_max, rho=1.0, device="cpu"):
40
+ """Constructs an polynomial in log sigma noise schedule"""
41
+ ramp = torch.linspace(1, 0, n, device=device) ** rho
42
+ sigmas = torch.exp(ramp * (math.log(sigma_max) - math.log(sigma_min)) + math.log(sigma_min))
43
+ return append_zero(sigmas)
44
+
45
+
46
+ def get_sigmas_vp(n, beta_d=19.9, beta_min=0.1, eps_s=1e-3, device="cpu"):
47
+ """Constructs a continuous VP noise schedule"""
48
+ t = torch.linspace(1, eps_s, n, device=device)
49
+ sigmas = torch.sqrt(torch.special.expm1(beta_d * t**2 / 2 + beta_min * t))
50
+ return append_zero(sigmas)
51
+
52
+
53
+ def to_d(x, sigma, denoised):
54
+ """Converts a denoiser output to a Karras ODE derivative"""
55
+ return (x - denoised) / utils.append_dims(sigma, x.ndim)
56
+
57
+
58
+ def get_ancestral_step(sigma_from, sigma_to, eta=1.0):
59
+ """Calculates the noise level (sigma_down) to step down to and the amount
60
+ of noise to add (sigma_up) when doing an ancestral sampling step"""
61
+ if not eta:
62
+ return sigma_to, 0.0
63
+ sigma_up = min(sigma_to, eta * (sigma_to**2 * (sigma_from**2 - sigma_to**2) / sigma_from**2) ** 0.5)
64
+ sigma_down = (sigma_to**2 - sigma_up**2) ** 0.5
65
+ return sigma_down, sigma_up
66
+
67
+
68
+ def default_noise_sampler(x):
69
+ return lambda sigma, sigma_next: torch.randn_like(x)
70
+
71
+
72
+ class BatchedBrownianTree:
73
+ """A wrapper around torchsde.BrownianTree that enables batches of entropy"""
74
+
75
+ def __init__(self, x, t0, t1, seed=None, **kwargs):
76
+ self.cpu_tree = kwargs.pop("cpu", True)
77
+ t0, t1, self.sign = self.sort(t0, t1)
78
+ w0 = kwargs.pop("w0", None)
79
+ if w0 is None:
80
+ w0 = torch.zeros_like(x)
81
+ self.batched = False
82
+ if seed is None:
83
+ seed = (torch.randint(0, 2**63 - 1, ()).item(),)
84
+ elif isinstance(seed, (tuple, list)):
85
+ if len(seed) != x.shape[0]:
86
+ raise ValueError("Passing a list or tuple of seeds to BatchedBrownianTree requires a length matching the batch size.")
87
+ self.batched = True
88
+ w0 = w0[0]
89
+ else:
90
+ seed = (seed,)
91
+ if self.cpu_tree:
92
+ t0, w0, t1 = t0.detach().cpu(), w0.detach().cpu(), t1.detach().cpu()
93
+ self.trees = tuple(torchsde.BrownianTree(t0, w0, t1, entropy=s, **kwargs) for s in seed)
94
+
95
+ @staticmethod
96
+ def sort(a, b):
97
+ return (a, b, 1) if a < b else (b, a, -1)
98
+
99
+ def __call__(self, t0, t1):
100
+ t0, t1, sign = self.sort(t0, t1)
101
+ device, dtype = t0.device, t0.dtype
102
+ if self.cpu_tree:
103
+ t0, t1 = t0.detach().cpu().float(), t1.detach().cpu().float()
104
+ w = torch.stack([tree(t0, t1) for tree in self.trees]).to(device=device, dtype=dtype) * (self.sign * sign)
105
+ return w if self.batched else w[0]
106
+
107
+
108
+ class BrownianTreeNoiseSampler:
109
+ """A noise sampler backed by a torchsde.BrownianTree.
110
+
111
+ Args:
112
+ x (Tensor): The tensor whose shape, device and dtype to use to generate
113
+ random samples.
114
+ sigma_min (float): The low end of the valid interval.
115
+ sigma_max (float): The high end of the valid interval.
116
+ seed (int or List[int]): The random seed. If a list of seeds is
117
+ supplied instead of a single integer, then the noise sampler will
118
+ use one BrownianTree per batch item, each with its own seed.
119
+ transform (callable): A function that maps sigma to the sampler's
120
+ internal timestep.
121
+ """
122
+
123
+ def __init__(self, x, sigma_min, sigma_max, seed=None, transform=lambda x: x, cpu=False):
124
+ self.transform = transform
125
+ t0, t1 = self.transform(torch.as_tensor(sigma_min)), self.transform(torch.as_tensor(sigma_max))
126
+ self.tree = BatchedBrownianTree(x, t0, t1, seed, cpu=cpu)
127
+
128
+ def __call__(self, sigma, sigma_next):
129
+ t0, t1 = self.transform(torch.as_tensor(sigma)), self.transform(torch.as_tensor(sigma_next))
130
+ return self.tree(t0, t1) / (t1 - t0).abs().sqrt()
131
+
132
+
133
+ def sigma_to_half_log_snr(sigma, model_sampling):
134
+ """Convert sigma to half-logSNR log(alpha_t / sigma_t)"""
135
+ if _is_const(model_sampling):
136
+ # log((1 - t) / t) = log((1 - sigma) / sigma)
137
+ return sigma.logit().neg()
138
+ return sigma.log().neg()
139
+
140
+
141
+ def half_log_snr_to_sigma(half_log_snr, model_sampling):
142
+ """Convert half-logSNR log(alpha_t / sigma_t) to sigma"""
143
+ if _is_const(model_sampling):
144
+ # 1 / (1 + exp(half_log_snr))
145
+ return half_log_snr.neg().sigmoid()
146
+ return half_log_snr.neg().exp()
147
+
148
+
149
+ def offset_first_sigma_for_snr(sigmas, model_sampling, percent_offset=1e-4):
150
+ """Adjust the first sigma to avoid invalid logSNR"""
151
+ if len(sigmas) <= 1:
152
+ return sigmas
153
+ if _is_const(model_sampling):
154
+ if sigmas[0] >= 1:
155
+ sigmas = sigmas.clone()
156
+ sigmas[0] = model_sampling.percent_to_sigma(percent_offset)
157
+ return sigmas
158
+
159
+
160
+ @torch.no_grad()
161
+ def sample_euler(model, x, sigmas, extra_args=None, callback=None, disable=None, s_churn=0.0, s_tmin=0.0, s_tmax=float("inf"), s_noise=1.0):
162
+ """Implements Algorithm 2 (Euler steps) from Karras et al. (2022)"""
163
+ extra_args = {} if extra_args is None else extra_args
164
+ s_in = x.new_ones([x.shape[0]])
165
+ for i in trange(len(sigmas) - 1, disable=disable):
166
+ if s_churn > 0:
167
+ gamma = min(s_churn / (len(sigmas) - 1), 2**0.5 - 1) if s_tmin <= sigmas[i] <= s_tmax else 0.0
168
+ sigma_hat = sigmas[i] * (gamma + 1)
169
+ else:
170
+ gamma = 0
171
+ sigma_hat = sigmas[i]
172
+
173
+ if gamma > 0:
174
+ eps = torch.randn_like(x) * s_noise
175
+ x = x + eps * (sigma_hat**2 - sigmas[i] ** 2) ** 0.5
176
+ denoised = model(x, sigma_hat * s_in, **extra_args)
177
+ d = to_d(x, sigma_hat, denoised)
178
+ if callback is not None:
179
+ callback({"x": x, "i": i, "sigma": sigmas[i], "sigma_hat": sigma_hat, "denoised": denoised})
180
+ dt = sigmas[i + 1] - sigma_hat
181
+ # Euler method
182
+ x = x + d * dt
183
+ return x
184
+
185
+
186
+ @torch.no_grad()
187
+ def sample_euler_ancestral(model, x, sigmas, extra_args=None, callback=None, disable=None, eta=1.0, s_noise=1.0, noise_sampler=None):
188
+ if _is_const(model.inner_model.predictor):
189
+ return sample_euler_ancestral_RF(model, x, sigmas, extra_args, callback, disable, eta, s_noise, noise_sampler)
190
+ """Ancestral sampling with Euler method steps"""
191
+ extra_args = {} if extra_args is None else extra_args
192
+
193
+ noise_sampler = default_noise_sampler(x) if noise_sampler is None else noise_sampler
194
+ s_in = x.new_ones([x.shape[0]])
195
+ for i in trange(len(sigmas) - 1, disable=disable):
196
+ denoised = model(x, sigmas[i] * s_in, **extra_args)
197
+ sigma_down, sigma_up = get_ancestral_step(sigmas[i], sigmas[i + 1], eta=eta)
198
+ if callback is not None:
199
+ callback({"x": x, "i": i, "sigma": sigmas[i], "sigma_hat": sigmas[i], "denoised": denoised})
200
+
201
+ if sigma_down == 0:
202
+ x = denoised
203
+ else:
204
+ d = to_d(x, sigmas[i], denoised)
205
+ # Euler method
206
+ dt = sigma_down - sigmas[i]
207
+ x = x + d * dt + noise_sampler(sigmas[i], sigmas[i + 1]) * s_noise * sigma_up
208
+ return x
209
+
210
+
211
+ @torch.no_grad()
212
+ def sample_euler_ancestral_RF(model, x, sigmas, extra_args=None, callback=None, disable=None, eta=1.0, s_noise=1.0, noise_sampler=None):
213
+ """Ancestral sampling with Euler method steps"""
214
+ extra_args = {} if extra_args is None else extra_args
215
+
216
+ noise_sampler = default_noise_sampler(x) if noise_sampler is None else noise_sampler
217
+ s_in = x.new_ones([x.shape[0]])
218
+ for i in trange(len(sigmas) - 1, disable=disable):
219
+ denoised = model(x, sigmas[i] * s_in, **extra_args)
220
+ # sigma_down, sigma_up = get_ancestral_step(sigmas[i], sigmas[i + 1], eta=eta)
221
+ if callback is not None:
222
+ callback({"x": x, "i": i, "sigma": sigmas[i], "sigma_hat": sigmas[i], "denoised": denoised})
223
+
224
+ if sigmas[i + 1] == 0:
225
+ x = denoised
226
+ else:
227
+ downstep_ratio = 1 + (sigmas[i + 1] / sigmas[i] - 1) * eta
228
+ sigma_down = sigmas[i + 1] * downstep_ratio
229
+ alpha_ip1 = 1 - sigmas[i + 1]
230
+ alpha_down = 1 - sigma_down
231
+ renoise_coeff = (sigmas[i + 1] ** 2 - sigma_down**2 * alpha_ip1**2 / alpha_down**2) ** 0.5
232
+ # Euler method
233
+ sigma_down_i_ratio = sigma_down / sigmas[i]
234
+ x = sigma_down_i_ratio * x + (1 - sigma_down_i_ratio) * denoised
235
+ if eta > 0:
236
+ x = (alpha_ip1 / alpha_down) * x + noise_sampler(sigmas[i], sigmas[i + 1]) * s_noise * renoise_coeff
237
+ return x
238
+
239
+
240
+ @torch.no_grad()
241
+ def sample_heun(model, x, sigmas, extra_args=None, callback=None, disable=None, s_churn=0.0, s_tmin=0.0, s_tmax=float("inf"), s_noise=1.0):
242
+ """Implements Algorithm 2 (Heun steps) from Karras et al. (2022)"""
243
+ extra_args = {} if extra_args is None else extra_args
244
+ s_in = x.new_ones([x.shape[0]])
245
+ for i in trange(len(sigmas) - 1, disable=disable):
246
+ if s_churn > 0:
247
+ gamma = min(s_churn / (len(sigmas) - 1), 2**0.5 - 1) if s_tmin <= sigmas[i] <= s_tmax else 0.0
248
+ sigma_hat = sigmas[i] * (gamma + 1)
249
+ else:
250
+ gamma = 0
251
+ sigma_hat = sigmas[i]
252
+
253
+ sigma_hat = sigmas[i] * (gamma + 1)
254
+ if gamma > 0:
255
+ eps = torch.randn_like(x) * s_noise
256
+ x = x + eps * (sigma_hat**2 - sigmas[i] ** 2) ** 0.5
257
+ denoised = model(x, sigma_hat * s_in, **extra_args)
258
+ d = to_d(x, sigma_hat, denoised)
259
+ if callback is not None:
260
+ callback({"x": x, "i": i, "sigma": sigmas[i], "sigma_hat": sigma_hat, "denoised": denoised})
261
+ dt = sigmas[i + 1] - sigma_hat
262
+ if sigmas[i + 1] == 0:
263
+ # Euler method
264
+ x = x + d * dt
265
+ else:
266
+ # Heun's method
267
+ x_2 = x + d * dt
268
+ denoised_2 = model(x_2, sigmas[i + 1] * s_in, **extra_args)
269
+ d_2 = to_d(x_2, sigmas[i + 1], denoised_2)
270
+ d_prime = (d + d_2) / 2
271
+ x = x + d_prime * dt
272
+ return x
273
+
274
+
275
+ @torch.no_grad()
276
+ def sample_dpm_2(model, x, sigmas, extra_args=None, callback=None, disable=None, s_churn=0.0, s_tmin=0.0, s_tmax=float("inf"), s_noise=1.0):
277
+ """A sampler inspired by DPM-Solver-2 and Algorithm 2 from Karras et al. (2022)"""
278
+ extra_args = {} if extra_args is None else extra_args
279
+ s_in = x.new_ones([x.shape[0]])
280
+ for i in trange(len(sigmas) - 1, disable=disable):
281
+ if s_churn > 0:
282
+ gamma = min(s_churn / (len(sigmas) - 1), 2**0.5 - 1) if s_tmin <= sigmas[i] <= s_tmax else 0.0
283
+ sigma_hat = sigmas[i] * (gamma + 1)
284
+ else:
285
+ gamma = 0
286
+ sigma_hat = sigmas[i]
287
+
288
+ if gamma > 0:
289
+ eps = torch.randn_like(x) * s_noise
290
+ x = x + eps * (sigma_hat**2 - sigmas[i] ** 2) ** 0.5
291
+ denoised = model(x, sigma_hat * s_in, **extra_args)
292
+ d = to_d(x, sigma_hat, denoised)
293
+ if callback is not None:
294
+ callback({"x": x, "i": i, "sigma": sigmas[i], "sigma_hat": sigma_hat, "denoised": denoised})
295
+ if sigmas[i + 1] == 0:
296
+ # Euler method
297
+ dt = sigmas[i + 1] - sigma_hat
298
+ x = x + d * dt
299
+ else:
300
+ # DPM-Solver-2
301
+ sigma_mid = sigma_hat.log().lerp(sigmas[i + 1].log(), 0.5).exp()
302
+ dt_1 = sigma_mid - sigma_hat
303
+ dt_2 = sigmas[i + 1] - sigma_hat
304
+ x_2 = x + d * dt_1
305
+ denoised_2 = model(x_2, sigma_mid * s_in, **extra_args)
306
+ d_2 = to_d(x_2, sigma_mid, denoised_2)
307
+ x = x + d_2 * dt_2
308
+ return x
309
+
310
+
311
+ def linear_multistep_coeff(order, t, i, j):
312
+ if order - 1 > i:
313
+ raise ValueError(f"Order {order} too high for step {i}")
314
+
315
+ def fn(tau):
316
+ prod = 1.0
317
+ for k in range(order):
318
+ if j == k:
319
+ continue
320
+ prod *= (tau - t[i - k]) / (t[i - j] - t[i - k])
321
+ return prod
322
+
323
+ return integrate.quad(fn, t[i], t[i + 1], epsrel=1e-4)[0]
324
+
325
+
326
+ @torch.no_grad()
327
+ def sample_lms(model, x, sigmas, extra_args=None, callback=None, disable=None, order=4):
328
+ extra_args = {} if extra_args is None else extra_args
329
+ s_in = x.new_ones([x.shape[0]])
330
+ sigmas_cpu = sigmas.detach().cpu().numpy()
331
+ ds = []
332
+ for i in trange(len(sigmas) - 1, disable=disable):
333
+ denoised = model(x, sigmas[i] * s_in, **extra_args)
334
+ d = to_d(x, sigmas[i], denoised)
335
+ ds.append(d)
336
+ if len(ds) > order:
337
+ ds.pop(0)
338
+ if callback is not None:
339
+ callback({"x": x, "i": i, "sigma": sigmas[i], "sigma_hat": sigmas[i], "denoised": denoised})
340
+ if sigmas[i + 1] == 0:
341
+ # Denoising step
342
+ x = denoised
343
+ else:
344
+ cur_order = min(i + 1, order)
345
+ coeffs = [linear_multistep_coeff(cur_order, sigmas_cpu, i, j) for j in range(cur_order)]
346
+ x = x + sum(coeff * d for coeff, d in zip(coeffs, reversed(ds)))
347
+ return x
348
+
349
+
350
+ @torch.no_grad()
351
+ def sample_dpmpp_2s_ancestral(model, x, sigmas, extra_args=None, callback=None, disable=None, eta=1.0, s_noise=1.0, noise_sampler=None):
352
+ if _is_const(model.inner_model.predictor):
353
+ return sample_dpmpp_2s_ancestral_RF(model, x, sigmas, extra_args, callback, disable, eta, s_noise, noise_sampler)
354
+
355
+ """Ancestral sampling with DPM-Solver++(2S) second-order steps"""
356
+ extra_args = {} if extra_args is None else extra_args
357
+
358
+ noise_sampler = default_noise_sampler(x) if noise_sampler is None else noise_sampler
359
+ s_in = x.new_ones([x.shape[0]])
360
+ sigma_fn = lambda t: t.neg().exp()
361
+ t_fn = lambda sigma: sigma.log().neg()
362
+
363
+ for i in trange(len(sigmas) - 1, disable=disable):
364
+ denoised = model(x, sigmas[i] * s_in, **extra_args)
365
+ sigma_down, sigma_up = get_ancestral_step(sigmas[i], sigmas[i + 1], eta=eta)
366
+ if callback is not None:
367
+ callback({"x": x, "i": i, "sigma": sigmas[i], "sigma_hat": sigmas[i], "denoised": denoised})
368
+ if sigma_down == 0:
369
+ # Euler method
370
+ d = to_d(x, sigmas[i], denoised)
371
+ dt = sigma_down - sigmas[i]
372
+ x = x + d * dt
373
+ else:
374
+ # DPM-Solver++(2S)
375
+ t, t_next = t_fn(sigmas[i]), t_fn(sigma_down)
376
+ r = 1 / 2
377
+ h = t_next - t
378
+ s = t + r * h
379
+ x_2 = (sigma_fn(s) / sigma_fn(t)) * x - (-h * r).expm1() * denoised
380
+ denoised_2 = model(x_2, sigma_fn(s) * s_in, **extra_args)
381
+ x = (sigma_fn(t_next) / sigma_fn(t)) * x - (-h).expm1() * denoised_2
382
+ # Noise addition
383
+ if sigmas[i + 1] > 0:
384
+ x = x + noise_sampler(sigmas[i], sigmas[i + 1]) * s_noise * sigma_up
385
+ return x
386
+
387
+
388
+ @torch.no_grad()
389
+ def sample_dpmpp_2s_ancestral_RF(model, x, sigmas, extra_args=None, callback=None, disable=None, eta=1.0, s_noise=1.0, noise_sampler=None):
390
+ """Ancestral sampling with DPM-Solver++(2S) second-order steps"""
391
+ extra_args = {} if extra_args is None else extra_args
392
+
393
+ noise_sampler = default_noise_sampler(x) if noise_sampler is None else noise_sampler
394
+ s_in = x.new_ones([x.shape[0]])
395
+ sigma_fn = lambda lbda: (lbda.exp() + 1) ** -1
396
+ lambda_fn = lambda sigma: ((1 - sigma) / sigma).log()
397
+
398
+ # logged_x = x.unsqueeze(0)
399
+
400
+ for i in trange(len(sigmas) - 1, disable=disable):
401
+ denoised = model(x, sigmas[i] * s_in, **extra_args)
402
+ downstep_ratio = 1 + (sigmas[i + 1] / sigmas[i] - 1) * eta
403
+ sigma_down = sigmas[i + 1] * downstep_ratio
404
+ alpha_ip1 = 1 - sigmas[i + 1]
405
+ alpha_down = 1 - sigma_down
406
+ renoise_coeff = (sigmas[i + 1] ** 2 - sigma_down**2 * alpha_ip1**2 / alpha_down**2) ** 0.5
407
+ # sigma_down, sigma_up = get_ancestral_step(sigmas[i], sigmas[i + 1], eta=eta)
408
+ if callback is not None:
409
+ callback({"x": x, "i": i, "sigma": sigmas[i], "sigma_hat": sigmas[i], "denoised": denoised})
410
+ if sigmas[i + 1] == 0:
411
+ # Euler method
412
+ d = to_d(x, sigmas[i], denoised)
413
+ dt = sigma_down - sigmas[i]
414
+ x = x + d * dt
415
+ else:
416
+ # DPM-Solver++(2S)
417
+ if sigmas[i] == 1.0:
418
+ sigma_s = 0.9999
419
+ else:
420
+ t_i, t_down = lambda_fn(sigmas[i]), lambda_fn(sigma_down)
421
+ r = 1 / 2
422
+ h = t_down - t_i
423
+ s = t_i + r * h
424
+ sigma_s = sigma_fn(s)
425
+ # sigma_s = sigmas[i+1]
426
+ sigma_s_i_ratio = sigma_s / sigmas[i]
427
+ u = sigma_s_i_ratio * x + (1 - sigma_s_i_ratio) * denoised
428
+ D_i = model(u, sigma_s * s_in, **extra_args)
429
+ sigma_down_i_ratio = sigma_down / sigmas[i]
430
+ x = sigma_down_i_ratio * x + (1 - sigma_down_i_ratio) * D_i
431
+ # print("sigma_i", sigmas[i], "sigma_ip1", sigmas[i+1],"sigma_down", sigma_down, "sigma_down_i_ratio", sigma_down_i_ratio, "sigma_s_i_ratio", sigma_s_i_ratio, "renoise_coeff", renoise_coeff)
432
+ # Noise addition
433
+ if sigmas[i + 1] > 0 and eta > 0:
434
+ x = (alpha_ip1 / alpha_down) * x + noise_sampler(sigmas[i], sigmas[i + 1]) * s_noise * renoise_coeff
435
+ # logged_x = torch.cat((logged_x, x.unsqueeze(0)), dim=0)
436
+ return x
437
+
438
+
439
+ @torch.no_grad()
440
+ def sample_dpmpp_sde(model, x, sigmas, extra_args=None, callback=None, disable=None, eta=1.0, s_noise=1.0, noise_sampler=None, r=1 / 2):
441
+ """DPM-Solver++ (stochastic)"""
442
+ if len(sigmas) <= 1:
443
+ return x
444
+
445
+ extra_args = {} if extra_args is None else extra_args
446
+ sigma_min, sigma_max = sigmas[sigmas > 0].min(), sigmas.max()
447
+ seed = extra_args.get("seed", None)
448
+ noise_sampler = BrownianTreeNoiseSampler(x, sigma_min, sigma_max, seed=seed, cpu=True) if noise_sampler is None else noise_sampler
449
+ s_in = x.new_ones([x.shape[0]])
450
+
451
+ model_sampling = model.inner_model.predictor
452
+ sigma_fn = partial(half_log_snr_to_sigma, model_sampling=model_sampling)
453
+ lambda_fn = partial(sigma_to_half_log_snr, model_sampling=model_sampling)
454
+ sigmas = offset_first_sigma_for_snr(sigmas, model_sampling)
455
+
456
+ for i in trange(len(sigmas) - 1, disable=disable):
457
+ denoised = model(x, sigmas[i] * s_in, **extra_args)
458
+ if callback is not None:
459
+ callback({"x": x, "i": i, "sigma": sigmas[i], "sigma_hat": sigmas[i], "denoised": denoised})
460
+ if sigmas[i + 1] == 0:
461
+ # Denoising step
462
+ x = denoised
463
+ else:
464
+ # DPM-Solver++
465
+ lambda_s, lambda_t = lambda_fn(sigmas[i]), lambda_fn(sigmas[i + 1])
466
+ h = lambda_t - lambda_s
467
+ lambda_s_1 = lambda_s + r * h
468
+ fac = 1 / (2 * r)
469
+
470
+ sigma_s_1 = sigma_fn(lambda_s_1)
471
+
472
+ alpha_s = sigmas[i] * lambda_s.exp()
473
+ alpha_s_1 = sigma_s_1 * lambda_s_1.exp()
474
+ alpha_t = sigmas[i + 1] * lambda_t.exp()
475
+
476
+ # Step 1
477
+ sd, su = get_ancestral_step(lambda_s.neg().exp(), lambda_s_1.neg().exp(), eta)
478
+ lambda_s_1_ = sd.log().neg()
479
+ h_ = lambda_s_1_ - lambda_s
480
+ x_2 = (alpha_s_1 / alpha_s) * (-h_).exp() * x - alpha_s_1 * (-h_).expm1() * denoised
481
+ if eta > 0 and s_noise > 0:
482
+ x_2 = x_2 + alpha_s_1 * noise_sampler(sigmas[i], sigma_s_1) * s_noise * su
483
+ denoised_2 = model(x_2, sigma_s_1 * s_in, **extra_args)
484
+
485
+ # Step 2
486
+ sd, su = get_ancestral_step(lambda_s.neg().exp(), lambda_t.neg().exp(), eta)
487
+ lambda_t_ = sd.log().neg()
488
+ h_ = lambda_t_ - lambda_s
489
+ denoised_d = (1 - fac) * denoised + fac * denoised_2
490
+ x = (alpha_t / alpha_s) * (-h_).exp() * x - alpha_t * (-h_).expm1() * denoised_d
491
+ if eta > 0 and s_noise > 0:
492
+ x = x + alpha_t * noise_sampler(sigmas[i], sigmas[i + 1]) * s_noise * su
493
+ return x
494
+
495
+
496
+ @torch.no_grad()
497
+ def sample_dpmpp_2m(model, x, sigmas, extra_args=None, callback=None, disable=None):
498
+ """DPM-Solver++(2M)"""
499
+ extra_args = {} if extra_args is None else extra_args
500
+ s_in = x.new_ones([x.shape[0]])
501
+ sigma_fn = lambda t: t.neg().exp()
502
+ t_fn = lambda sigma: sigma.log().neg()
503
+ old_denoised = None
504
+
505
+ for i in trange(len(sigmas) - 1, disable=disable):
506
+ denoised = model(x, sigmas[i] * s_in, **extra_args)
507
+ if callback is not None:
508
+ callback({"x": x, "i": i, "sigma": sigmas[i], "sigma_hat": sigmas[i], "denoised": denoised})
509
+ t, t_next = t_fn(sigmas[i]), t_fn(sigmas[i + 1])
510
+ h = t_next - t
511
+ if old_denoised is None or sigmas[i + 1] == 0:
512
+ x = (sigma_fn(t_next) / sigma_fn(t)) * x - (-h).expm1() * denoised
513
+ else:
514
+ h_last = t - t_fn(sigmas[i - 1])
515
+ r = h_last / h
516
+ denoised_d = (1 + 1 / (2 * r)) * denoised - (1 / (2 * r)) * old_denoised
517
+ x = (sigma_fn(t_next) / sigma_fn(t)) * x - (-h).expm1() * denoised_d
518
+ old_denoised = denoised
519
+ return x
520
+
521
+
522
+ @torch.no_grad()
523
+ def sample_dpmpp_2m_sde(model, x, sigmas, extra_args=None, callback=None, disable=None, eta=1.0, s_noise=1.0, noise_sampler=None, solver_type="midpoint"):
524
+ """DPM-Solver++(2M) SDE"""
525
+ if len(sigmas) <= 1:
526
+ return x
527
+
528
+ if solver_type not in {"heun", "midpoint"}:
529
+ raise ValueError("solver_type must be 'heun' or 'midpoint'")
530
+
531
+ extra_args = {} if extra_args is None else extra_args
532
+ seed = extra_args.get("seed", None)
533
+ sigma_min, sigma_max = sigmas[sigmas > 0].min(), sigmas.max()
534
+ noise_sampler = BrownianTreeNoiseSampler(x, sigma_min, sigma_max, seed=seed, cpu=True) if noise_sampler is None else noise_sampler
535
+ s_in = x.new_ones([x.shape[0]])
536
+
537
+ model_sampling = model.inner_model.predictor
538
+ lambda_fn = partial(sigma_to_half_log_snr, model_sampling=model_sampling)
539
+ sigmas = offset_first_sigma_for_snr(sigmas, model_sampling)
540
+
541
+ old_denoised = None
542
+ h, h_last = None, None
543
+
544
+ for i in trange(len(sigmas) - 1, disable=disable):
545
+ denoised = model(x, sigmas[i] * s_in, **extra_args)
546
+ if callback is not None:
547
+ callback({"x": x, "i": i, "sigma": sigmas[i], "sigma_hat": sigmas[i], "denoised": denoised})
548
+ if sigmas[i + 1] == 0:
549
+ # Denoising step
550
+ x = denoised
551
+ else:
552
+ # DPM-Solver++(2M) SDE
553
+ lambda_s, lambda_t = lambda_fn(sigmas[i]), lambda_fn(sigmas[i + 1])
554
+ h = lambda_t - lambda_s
555
+ h_eta = h * (eta + 1)
556
+
557
+ alpha_t = sigmas[i + 1] * lambda_t.exp()
558
+
559
+ x = sigmas[i + 1] / sigmas[i] * (-h * eta).exp() * x + alpha_t * (-h_eta).expm1().neg() * denoised
560
+
561
+ if old_denoised is not None:
562
+ r = h_last / h
563
+ if solver_type == "heun":
564
+ x = x + alpha_t * ((-h_eta).expm1().neg() / (-h_eta) + 1) * (1 / r) * (denoised - old_denoised)
565
+ elif solver_type == "midpoint":
566
+ x = x + 0.5 * alpha_t * (-h_eta).expm1().neg() * (1 / r) * (denoised - old_denoised)
567
+
568
+ if eta > 0 and s_noise > 0:
569
+ x = x + noise_sampler(sigmas[i], sigmas[i + 1]) * sigmas[i + 1] * (-2 * h * eta).expm1().neg().sqrt() * s_noise
570
+
571
+ old_denoised = denoised
572
+ h_last = h
573
+ return x
574
+
575
+
576
+ @torch.no_grad()
577
+ def sample_dpmpp_3m_sde(model, x, sigmas, extra_args=None, callback=None, disable=None, eta=1.0, s_noise=1.0, noise_sampler=None):
578
+ """DPM-Solver++(3M) SDE"""
579
+
580
+ if len(sigmas) <= 1:
581
+ return x
582
+
583
+ extra_args = {} if extra_args is None else extra_args
584
+ seed = extra_args.get("seed", None)
585
+ sigma_min, sigma_max = sigmas[sigmas > 0].min(), sigmas.max()
586
+ noise_sampler = BrownianTreeNoiseSampler(x, sigma_min, sigma_max, seed=seed, cpu=True) if noise_sampler is None else noise_sampler
587
+ s_in = x.new_ones([x.shape[0]])
588
+
589
+ model_sampling = model.inner_model.predictor
590
+ lambda_fn = partial(sigma_to_half_log_snr, model_sampling=model_sampling)
591
+ sigmas = offset_first_sigma_for_snr(sigmas, model_sampling)
592
+
593
+ denoised_1, denoised_2 = None, None
594
+ h, h_1, h_2 = None, None, None
595
+
596
+ for i in trange(len(sigmas) - 1, disable=disable):
597
+ denoised = model(x, sigmas[i] * s_in, **extra_args)
598
+ if callback is not None:
599
+ callback({"x": x, "i": i, "sigma": sigmas[i], "sigma_hat": sigmas[i], "denoised": denoised})
600
+ if sigmas[i + 1] == 0:
601
+ # Denoising step
602
+ x = denoised
603
+ else:
604
+ lambda_s, lambda_t = lambda_fn(sigmas[i]), lambda_fn(sigmas[i + 1])
605
+ h = lambda_t - lambda_s
606
+ h_eta = h * (eta + 1)
607
+
608
+ alpha_t = sigmas[i + 1] * lambda_t.exp()
609
+
610
+ x = sigmas[i + 1] / sigmas[i] * (-h * eta).exp() * x + alpha_t * (-h_eta).expm1().neg() * denoised
611
+
612
+ if h_2 is not None:
613
+ # DPM-Solver++(3M) SDE
614
+ r0 = h_1 / h
615
+ r1 = h_2 / h
616
+ d1_0 = (denoised - denoised_1) / r0
617
+ d1_1 = (denoised_1 - denoised_2) / r1
618
+ d1 = d1_0 + (d1_0 - d1_1) * r0 / (r0 + r1)
619
+ d2 = (d1_0 - d1_1) / (r0 + r1)
620
+ phi_2 = h_eta.neg().expm1() / h_eta + 1
621
+ phi_3 = phi_2 / h_eta - 0.5
622
+ x = x + (alpha_t * phi_2) * d1 - (alpha_t * phi_3) * d2
623
+ elif h_1 is not None:
624
+ # DPM-Solver++(2M) SDE
625
+ r = h_1 / h
626
+ d = (denoised - denoised_1) / r
627
+ phi_2 = h_eta.neg().expm1() / h_eta + 1
628
+ x = x + (alpha_t * phi_2) * d
629
+
630
+ if eta > 0 and s_noise > 0:
631
+ x = x + noise_sampler(sigmas[i], sigmas[i + 1]) * sigmas[i + 1] * (-2 * h * eta).expm1().neg().sqrt() * s_noise
632
+
633
+ denoised_1, denoised_2 = denoised, denoised_1
634
+ h_1, h_2 = h, h_1
635
+ return x
636
+
637
+
638
+ @torch.no_grad()
639
+ def sample_lcm(model, x, sigmas, extra_args=None, callback=None, disable=None, noise_sampler=None):
640
+ extra_args = {} if extra_args is None else extra_args
641
+
642
+ noise_sampler = default_noise_sampler(x) if noise_sampler is None else noise_sampler
643
+ s_in = x.new_ones([x.shape[0]])
644
+ for i in trange(len(sigmas) - 1, disable=disable):
645
+ denoised = model(x, sigmas[i] * s_in, **extra_args)
646
+ if callback is not None:
647
+ callback({"x": x, "i": i, "sigma": sigmas[i], "sigma_hat": sigmas[i], "denoised": denoised})
648
+
649
+ x = denoised
650
+ if sigmas[i + 1] > 0:
651
+ x = model.inner_model.predictor.noise_scaling(sigmas[i + 1], noise_sampler(sigmas[i], sigmas[i + 1]), x)
652
+ return x
653
+
654
+
655
+ @torch.no_grad()
656
+ def sample_euler_ancestral_cfg_pp(model, x, sigmas, extra_args=None, callback=None, disable=None, eta=1.0, s_noise=1.0, noise_sampler=None):
657
+ """Ancestral sampling with Euler method steps (CFG++)"""
658
+ extra_args = {} if extra_args is None else extra_args
659
+
660
+ noise_sampler = default_noise_sampler(x) if noise_sampler is None else noise_sampler
661
+
662
+ model_sampling = model.inner_model.predictor
663
+ lambda_fn = partial(sigma_to_half_log_snr, model_sampling=model_sampling)
664
+
665
+ uncond_denoised = None
666
+
667
+ def post_cfg_function(args):
668
+ nonlocal uncond_denoised
669
+ uncond_denoised = args["uncond_denoised"]
670
+ return args["denoised"]
671
+
672
+ model_options = extra_args.get("model_options", {}).copy()
673
+ extra_args["model_options"] = set_model_options_post_cfg_function(model_options, post_cfg_function, disable_cfg1_optimization=True)
674
+
675
+ s_in = x.new_ones([x.shape[0]])
676
+ for i in trange(len(sigmas) - 1, disable=disable):
677
+ denoised = model(x, sigmas[i] * s_in, **extra_args)
678
+ if callback is not None:
679
+ callback({"x": x, "i": i, "sigma": sigmas[i], "sigma_hat": sigmas[i], "denoised": denoised})
680
+ if sigmas[i + 1] == 0:
681
+ # Denoising step
682
+ x = denoised
683
+ else:
684
+ alpha_s = sigmas[i] * lambda_fn(sigmas[i]).exp()
685
+ alpha_t = sigmas[i + 1] * lambda_fn(sigmas[i + 1]).exp()
686
+ d = to_d(x, sigmas[i], alpha_s * uncond_denoised) # to noise
687
+
688
+ # DDIM stochastic sampling
689
+ sigma_down, sigma_up = get_ancestral_step(sigmas[i] / alpha_s, sigmas[i + 1] / alpha_t, eta=eta)
690
+ sigma_down = alpha_t * sigma_down
691
+
692
+ # Euler method
693
+ x = alpha_t * denoised + sigma_down * d
694
+ if eta > 0 and s_noise > 0:
695
+ x = x + alpha_t * noise_sampler(sigmas[i], sigmas[i + 1]) * s_noise * sigma_up
696
+ return x
697
+
698
+
699
+ @torch.no_grad()
700
+ def sample_euler_cfg_pp(model, x, sigmas, extra_args=None, callback=None, disable=None):
701
+ """Euler method steps (CFG++)"""
702
+ return sample_euler_ancestral_cfg_pp(model, x, sigmas, extra_args=extra_args, callback=callback, disable=disable, eta=0.0, s_noise=0.0, noise_sampler=None)
703
+
704
+
705
+ @torch.no_grad()
706
+ def sample_dpmpp_2m_cfg_pp(model, x, sigmas, extra_args=None, callback=None, disable=None):
707
+ """DPM-Solver++(2M)"""
708
+ extra_args = {} if extra_args is None else extra_args
709
+ s_in = x.new_ones([x.shape[0]])
710
+ t_fn = lambda sigma: sigma.log().neg()
711
+
712
+ old_uncond_denoised = None
713
+ uncond_denoised = None
714
+
715
+ def post_cfg_function(args):
716
+ nonlocal uncond_denoised
717
+ uncond_denoised = args["uncond_denoised"]
718
+ return args["denoised"]
719
+
720
+ model_options = extra_args.get("model_options", {}).copy()
721
+ extra_args["model_options"] = set_model_options_post_cfg_function(model_options, post_cfg_function, disable_cfg1_optimization=True)
722
+
723
+ for i in trange(len(sigmas) - 1, disable=disable):
724
+ denoised = model(x, sigmas[i] * s_in, **extra_args)
725
+ if callback is not None:
726
+ callback({"x": x, "i": i, "sigma": sigmas[i], "sigma_hat": sigmas[i], "denoised": denoised})
727
+ t, t_next = t_fn(sigmas[i]), t_fn(sigmas[i + 1])
728
+ h = t_next - t
729
+ if old_uncond_denoised is None or sigmas[i + 1] == 0:
730
+ denoised_mix = -torch.exp(-h) * uncond_denoised
731
+ else:
732
+ h_last = t - t_fn(sigmas[i - 1])
733
+ r = h_last / h
734
+ denoised_mix = -torch.exp(-h) * uncond_denoised - torch.expm1(-h) * (1 / (2 * r)) * (denoised - old_uncond_denoised)
735
+ x = denoised + denoised_mix + torch.exp(-h) * x
736
+ old_uncond_denoised = uncond_denoised
737
+ return x
738
+
739
+
740
+ @torch.no_grad()
741
+ def res_multistep(model, x, sigmas, extra_args=None, callback=None, disable=None, s_noise=1.0, noise_sampler=None, eta=1.0, cfg_pp=False):
742
+ extra_args = {} if extra_args is None else extra_args
743
+
744
+ noise_sampler = default_noise_sampler(x) if noise_sampler is None else noise_sampler
745
+ s_in = x.new_ones([x.shape[0]])
746
+ sigma_fn = lambda t: t.neg().exp()
747
+ t_fn = lambda sigma: sigma.log().neg()
748
+ phi1_fn = lambda t: torch.expm1(t) / t
749
+ phi2_fn = lambda t: (phi1_fn(t) - 1.0) / t
750
+
751
+ old_sigma_down = None
752
+ old_denoised = None
753
+ uncond_denoised = None
754
+
755
+ def post_cfg_function(args):
756
+ nonlocal uncond_denoised
757
+ uncond_denoised = args["uncond_denoised"]
758
+ return args["denoised"]
759
+
760
+ if cfg_pp:
761
+ model_options = extra_args.get("model_options", {}).copy()
762
+ extra_args["model_options"] = set_model_options_post_cfg_function(model_options, post_cfg_function, disable_cfg1_optimization=True)
763
+
764
+ for i in trange(len(sigmas) - 1, disable=disable):
765
+ denoised = model(x, sigmas[i] * s_in, **extra_args)
766
+ sigma_down, sigma_up = get_ancestral_step(sigmas[i], sigmas[i + 1], eta=eta)
767
+ if callback is not None:
768
+ callback({"x": x, "i": i, "sigma": sigmas[i], "sigma_hat": sigmas[i], "denoised": denoised})
769
+ if sigma_down == 0 or old_denoised is None:
770
+ # Euler method
771
+ if cfg_pp:
772
+ d = to_d(x, sigmas[i], uncond_denoised)
773
+ x = denoised + d * sigma_down
774
+ else:
775
+ d = to_d(x, sigmas[i], denoised)
776
+ dt = sigma_down - sigmas[i]
777
+ x = x + d * dt
778
+ else:
779
+ # Second order multistep method in https://arxiv.org/pdf/2308.02157
780
+ t, t_old, t_next, t_prev = t_fn(sigmas[i]), t_fn(old_sigma_down), t_fn(sigma_down), t_fn(sigmas[i - 1])
781
+ h = t_next - t
782
+ c2 = (t_prev - t_old) / h
783
+
784
+ phi1_val, phi2_val = phi1_fn(-h), phi2_fn(-h)
785
+ b1 = torch.nan_to_num(phi1_val - phi2_val / c2, nan=0.0)
786
+ b2 = torch.nan_to_num(phi2_val / c2, nan=0.0)
787
+
788
+ if cfg_pp:
789
+ x = x + (denoised - uncond_denoised)
790
+ x = sigma_fn(h) * x + h * (b1 * uncond_denoised + b2 * old_denoised)
791
+ else:
792
+ x = sigma_fn(h) * x + h * (b1 * denoised + b2 * old_denoised)
793
+
794
+ # Noise addition
795
+ if sigmas[i + 1] > 0:
796
+ x = x + noise_sampler(sigmas[i], sigmas[i + 1]) * s_noise * sigma_up
797
+
798
+ if cfg_pp:
799
+ old_denoised = uncond_denoised
800
+ else:
801
+ old_denoised = denoised
802
+ old_sigma_down = sigma_down
803
+ return x
804
+
805
+
806
+ @torch.no_grad()
807
+ def sample_res_multistep(model, x, sigmas, extra_args=None, callback=None, disable=None, s_noise=1.0, noise_sampler=None):
808
+ return res_multistep(model, x, sigmas, extra_args=extra_args, callback=callback, disable=disable, s_noise=s_noise, noise_sampler=noise_sampler, eta=0.0, cfg_pp=False)
809
+
810
+
811
+ @torch.no_grad()
812
+ def sample_Kohaku_LoNyu_Yog(model, x, sigmas, extra_args=None, callback=None, disable=None, s_churn=None, s_tmin=None, s_tmax=float("inf"), s_noise=None, noise_sampler=None, eta=None):
813
+ s_churn = 0.0 if s_churn is None else s_churn
814
+ s_tmin = 0.0 if s_tmin is None else s_tmin
815
+ s_noise = 1.0 if s_noise is None else s_noise
816
+ eta = 1.0 if eta is None else eta
817
+
818
+ extra_args = {} if extra_args is None else extra_args
819
+ s_in = x.new_ones([x.shape[0]])
820
+ noise_sampler = default_noise_sampler(x) if noise_sampler is None else noise_sampler
821
+ for i in trange(len(sigmas) - 1, disable=disable):
822
+ gamma = min(s_churn / (len(sigmas) - 1), 2**0.5 - 1) if s_tmin <= sigmas[i] <= s_tmax else 0.0
823
+ eps = torch.randn_like(x) * s_noise
824
+ sigma_hat = sigmas[i] * (gamma + 1)
825
+ if gamma > 0:
826
+ x = x + eps * (sigma_hat**2 - sigmas[i] ** 2) ** 0.5
827
+ denoised = model(x, sigma_hat * s_in, **extra_args)
828
+ d = to_d(x, sigma_hat, denoised)
829
+ sigma_down, sigma_up = get_ancestral_step(sigmas[i], sigmas[i + 1], eta=eta)
830
+ if callback is not None:
831
+ callback({"x": x, "i": i, "sigma": sigmas[i], "sigma_hat": sigma_hat, "denoised": denoised})
832
+ dt = sigma_down - sigmas[i]
833
+ if i <= (len(sigmas) - 1) / 2:
834
+ x2 = -x
835
+ denoised2 = model(x2, sigma_hat * s_in, **extra_args)
836
+ d2 = to_d(x2, sigma_hat, denoised2)
837
+ x3 = x + ((d + d2) / 2) * dt
838
+ denoised3 = model(x3, sigma_hat * s_in, **extra_args)
839
+ d3 = to_d(x3, sigma_hat, denoised3)
840
+ real_d = (d + d3) / 2
841
+ x = x + real_d * dt
842
+ x = x + noise_sampler(sigmas[i], sigmas[i + 1]) * s_noise * sigma_up
843
+ else:
844
+ x = x + d * dt
845
+ return x
modules_forge/packages/k_diffusion/utils.py ADDED
@@ -0,0 +1,447 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import hashlib
2
+ import math
3
+ import shutil
4
+ import threading
5
+ import urllib
6
+ import warnings
7
+ from contextlib import contextmanager
8
+ from pathlib import Path
9
+
10
+ import safetensors
11
+ import torch
12
+ from PIL import Image
13
+ from torch import nn, optim
14
+ from torch.utils import data
15
+ from torchvision.transforms import functional as TF
16
+
17
+
18
+ def from_pil_image(x):
19
+ """Converts from a PIL image to a tensor"""
20
+ x = TF.to_tensor(x)
21
+ if x.ndim == 2:
22
+ x = x[..., None]
23
+ return x * 2 - 1
24
+
25
+
26
+ def to_pil_image(x):
27
+ """Converts from a tensor to a PIL image"""
28
+ if x.ndim == 4:
29
+ assert x.shape[0] == 1
30
+ x = x[0]
31
+ if x.shape[0] == 1:
32
+ x = x[0]
33
+ return TF.to_pil_image((x.clamp(-1, 1) + 1) / 2)
34
+
35
+
36
+ def hf_datasets_augs_helper(examples, transform, image_key, mode="RGB"):
37
+ """Apply passed in transforms for HuggingFace Datasets"""
38
+ images = [transform(image.convert(mode)) for image in examples[image_key]]
39
+ return {image_key: images}
40
+
41
+
42
+ def append_dims(x, target_dims):
43
+ """Appends dimensions to the end of a tensor until it has target_dims dimensions"""
44
+ dims_to_append = target_dims - x.ndim
45
+ if dims_to_append < 0:
46
+ raise ValueError(f"input has {x.ndim} dims but target_dims is {target_dims}, which is less")
47
+ return x[(...,) + (None,) * dims_to_append]
48
+
49
+
50
+ def n_params(module):
51
+ """Returns the number of trainable parameters in a module"""
52
+ return sum(p.numel() for p in module.parameters())
53
+
54
+
55
+ def download_file(path, url, digest=None):
56
+ """Downloads a file if it does not exist, optionally checking its SHA-256 hash"""
57
+ path = Path(path)
58
+ path.parent.mkdir(parents=True, exist_ok=True)
59
+ if not path.exists():
60
+ with urllib.request.urlopen(url) as response, open(path, "wb") as f:
61
+ shutil.copyfileobj(response, f)
62
+ if digest is not None:
63
+ file_digest = hashlib.sha256(open(path, "rb").read()).hexdigest()
64
+ if digest != file_digest:
65
+ raise OSError(f"hash of {path} (url: {url}) failed to validate")
66
+ return path
67
+
68
+
69
+ @contextmanager
70
+ def train_mode(model, mode=True):
71
+ """A context manager that places a model into training mode and restores
72
+ the previous mode on exit"""
73
+ modes = [module.training for module in model.modules()]
74
+ try:
75
+ yield model.train(mode)
76
+ finally:
77
+ for i, module in enumerate(model.modules()):
78
+ module.training = modes[i]
79
+
80
+
81
+ def eval_mode(model):
82
+ """A context manager that places a model into evaluation mode and restores
83
+ the previous mode on exit"""
84
+ return train_mode(model, False)
85
+
86
+
87
+ @torch.no_grad()
88
+ def ema_update(model, averaged_model, decay):
89
+ """Incorporates updated model parameters into an exponential moving averaged
90
+ version of a model. It should be called after each optimizer step"""
91
+ model_params = dict(model.named_parameters())
92
+ averaged_params = dict(averaged_model.named_parameters())
93
+ assert model_params.keys() == averaged_params.keys()
94
+
95
+ for name, param in model_params.items():
96
+ averaged_params[name].lerp_(param, 1 - decay)
97
+
98
+ model_buffers = dict(model.named_buffers())
99
+ averaged_buffers = dict(averaged_model.named_buffers())
100
+ assert model_buffers.keys() == averaged_buffers.keys()
101
+
102
+ for name, buf in model_buffers.items():
103
+ averaged_buffers[name].copy_(buf)
104
+
105
+
106
+ class EMAWarmup:
107
+ """Implements an EMA warmup using an inverse decay schedule.
108
+ If inv_gamma=1 and power=1, implements a simple average. inv_gamma=1, power=2/3 are
109
+ good values for models you plan to train for a million or more steps (reaches decay
110
+ factor 0.999 at 31.6K steps, 0.9999 at 1M steps), inv_gamma=1, power=3/4 for models
111
+ you plan to train for less (reaches decay factor 0.999 at 10K steps, 0.9999 at
112
+ 215.4k steps).
113
+ Args:
114
+ inv_gamma (float): Inverse multiplicative factor of EMA warmup. Default: 1.
115
+ power (float): Exponential factor of EMA warmup. Default: 1.
116
+ min_value (float): The minimum EMA decay rate. Default: 0.
117
+ max_value (float): The maximum EMA decay rate. Default: 1.
118
+ start_at (int): The epoch to start averaging at. Default: 0.
119
+ last_epoch (int): The index of last epoch. Default: 0.
120
+ """
121
+
122
+ def __init__(self, inv_gamma=1.0, power=1.0, min_value=0.0, max_value=1.0, start_at=0, last_epoch=0):
123
+ self.inv_gamma = inv_gamma
124
+ self.power = power
125
+ self.min_value = min_value
126
+ self.max_value = max_value
127
+ self.start_at = start_at
128
+ self.last_epoch = last_epoch
129
+
130
+ def state_dict(self):
131
+ """Returns the state of the class as a :class:`dict`"""
132
+ return dict(self.__dict__.items())
133
+
134
+ def load_state_dict(self, state_dict):
135
+ """Loads the class's state.
136
+ Args:
137
+ state_dict (dict): scaler state. Should be an object returned
138
+ from a call to :meth:`state_dict`.
139
+ """
140
+ self.__dict__.update(state_dict)
141
+
142
+ def get_value(self):
143
+ """Gets the current EMA decay rate"""
144
+ epoch = max(0, self.last_epoch - self.start_at)
145
+ value = 1 - (1 + epoch / self.inv_gamma) ** -self.power
146
+ return 0.0 if epoch < 0 else min(self.max_value, max(self.min_value, value))
147
+
148
+ def step(self):
149
+ """Updates the step count"""
150
+ self.last_epoch += 1
151
+
152
+
153
+ class InverseLR(optim.lr_scheduler._LRScheduler):
154
+ """Implements an inverse decay learning rate schedule with an optional exponential
155
+ warmup. When last_epoch=-1, sets initial lr as lr.
156
+ inv_gamma is the number of steps/epochs required for the learning rate to decay to
157
+ (1 / 2)**power of its original value.
158
+ Args:
159
+ optimizer (Optimizer): Wrapped optimizer.
160
+ inv_gamma (float): Inverse multiplicative factor of learning rate decay. Default: 1.
161
+ power (float): Exponential factor of learning rate decay. Default: 1.
162
+ warmup (float): Exponential warmup factor (0 <= warmup < 1, 0 to disable)
163
+ Default: 0.
164
+ min_lr (float): The minimum learning rate. Default: 0.
165
+ last_epoch (int): The index of last epoch. Default: -1.
166
+ verbose (bool): If ``True``, prints a message to stdout for
167
+ each update. Default: ``False``.
168
+ """
169
+
170
+ def __init__(self, optimizer, inv_gamma=1.0, power=1.0, warmup=0.0, min_lr=0.0, last_epoch=-1, verbose=False):
171
+ self.inv_gamma = inv_gamma
172
+ self.power = power
173
+ if not 0.0 <= warmup < 1:
174
+ raise ValueError("Invalid value for warmup")
175
+ self.warmup = warmup
176
+ self.min_lr = min_lr
177
+ super().__init__(optimizer, last_epoch, verbose)
178
+
179
+ def get_lr(self):
180
+ if not self._get_lr_called_within_step:
181
+ warnings.warn("To get the last learning rate computed by the scheduler, " "please use `get_last_lr()`.")
182
+
183
+ return self._get_closed_form_lr()
184
+
185
+ def _get_closed_form_lr(self):
186
+ warmup = 1 - self.warmup ** (self.last_epoch + 1)
187
+ lr_mult = (1 + self.last_epoch / self.inv_gamma) ** -self.power
188
+ return [warmup * max(self.min_lr, base_lr * lr_mult) for base_lr in self.base_lrs]
189
+
190
+
191
+ class ExponentialLR(optim.lr_scheduler._LRScheduler):
192
+ """Implements an exponential learning rate schedule with an optional exponential
193
+ warmup. When last_epoch=-1, sets initial lr as lr. Decays the learning rate
194
+ continuously by decay (default 0.5) every num_steps steps.
195
+ Args:
196
+ optimizer (Optimizer): Wrapped optimizer.
197
+ num_steps (float): The number of steps to decay the learning rate by decay in.
198
+ decay (float): The factor by which to decay the learning rate every num_steps
199
+ steps. Default: 0.5.
200
+ warmup (float): Exponential warmup factor (0 <= warmup < 1, 0 to disable)
201
+ Default: 0.
202
+ min_lr (float): The minimum learning rate. Default: 0.
203
+ last_epoch (int): The index of last epoch. Default: -1.
204
+ verbose (bool): If ``True``, prints a message to stdout for
205
+ each update. Default: ``False``.
206
+ """
207
+
208
+ def __init__(self, optimizer, num_steps, decay=0.5, warmup=0.0, min_lr=0.0, last_epoch=-1, verbose=False):
209
+ self.num_steps = num_steps
210
+ self.decay = decay
211
+ if not 0.0 <= warmup < 1:
212
+ raise ValueError("Invalid value for warmup")
213
+ self.warmup = warmup
214
+ self.min_lr = min_lr
215
+ super().__init__(optimizer, last_epoch, verbose)
216
+
217
+ def get_lr(self):
218
+ if not self._get_lr_called_within_step:
219
+ warnings.warn("To get the last learning rate computed by the scheduler, " "please use `get_last_lr()`.")
220
+
221
+ return self._get_closed_form_lr()
222
+
223
+ def _get_closed_form_lr(self):
224
+ warmup = 1 - self.warmup ** (self.last_epoch + 1)
225
+ lr_mult = (self.decay ** (1 / self.num_steps)) ** self.last_epoch
226
+ return [warmup * max(self.min_lr, base_lr * lr_mult) for base_lr in self.base_lrs]
227
+
228
+
229
+ class ConstantLRWithWarmup(optim.lr_scheduler._LRScheduler):
230
+ """Implements a constant learning rate schedule with an optional exponential
231
+ warmup. When last_epoch=-1, sets initial lr as lr.
232
+ Args:
233
+ optimizer (Optimizer): Wrapped optimizer.
234
+ warmup (float): Exponential warmup factor (0 <= warmup < 1, 0 to disable)
235
+ Default: 0.
236
+ last_epoch (int): The index of last epoch. Default: -1.
237
+ verbose (bool): If ``True``, prints a message to stdout for
238
+ each update. Default: ``False``.
239
+ """
240
+
241
+ def __init__(self, optimizer, warmup=0.0, last_epoch=-1, verbose=False):
242
+ if not 0.0 <= warmup < 1:
243
+ raise ValueError("Invalid value for warmup")
244
+ self.warmup = warmup
245
+ super().__init__(optimizer, last_epoch, verbose)
246
+
247
+ def get_lr(self):
248
+ if not self._get_lr_called_within_step:
249
+ warnings.warn("To get the last learning rate computed by the scheduler, " "please use `get_last_lr()`.")
250
+
251
+ return self._get_closed_form_lr()
252
+
253
+ def _get_closed_form_lr(self):
254
+ warmup = 1 - self.warmup ** (self.last_epoch + 1)
255
+ return [warmup * base_lr for base_lr in self.base_lrs]
256
+
257
+
258
+ def stratified_uniform(shape, group=0, groups=1, dtype=None, device=None):
259
+ """Draws stratified samples from a uniform distribution"""
260
+ if groups <= 0:
261
+ raise ValueError(f"groups must be positive, got {groups}")
262
+ if group < 0 or group >= groups:
263
+ raise ValueError(f"group must be in [0, {groups})")
264
+ n = shape[-1] * groups
265
+ offsets = torch.arange(group, n, groups, dtype=dtype, device=device)
266
+ u = torch.rand(shape, dtype=dtype, device=device)
267
+ return (offsets + u) / n
268
+
269
+
270
+ stratified_settings = threading.local()
271
+
272
+
273
+ @contextmanager
274
+ def enable_stratified(group=0, groups=1, disable=False):
275
+ """A context manager that enables stratified sampling"""
276
+ try:
277
+ stratified_settings.disable = disable
278
+ stratified_settings.group = group
279
+ stratified_settings.groups = groups
280
+ yield
281
+ finally:
282
+ del stratified_settings.disable
283
+ del stratified_settings.group
284
+ del stratified_settings.groups
285
+
286
+
287
+ @contextmanager
288
+ def enable_stratified_accelerate(accelerator, disable=False):
289
+ """A context manager that enables stratified sampling, distributing the strata across
290
+ all processes and gradient accumulation steps using settings from Hugging Face Accelerate"""
291
+ try:
292
+ rank = accelerator.process_index
293
+ world_size = accelerator.num_processes
294
+ acc_steps = accelerator.gradient_state.num_steps
295
+ acc_step = accelerator.step % acc_steps
296
+ group = rank * acc_steps + acc_step
297
+ groups = world_size * acc_steps
298
+ with enable_stratified(group, groups, disable=disable):
299
+ yield
300
+ finally:
301
+ pass
302
+
303
+
304
+ def stratified_with_settings(shape, dtype=None, device=None):
305
+ """Draws stratified samples from a uniform distribution, using settings from a context
306
+ manager"""
307
+ if not hasattr(stratified_settings, "disable") or stratified_settings.disable:
308
+ return torch.rand(shape, dtype=dtype, device=device)
309
+ return stratified_uniform(shape, stratified_settings.group, stratified_settings.groups, dtype=dtype, device=device)
310
+
311
+
312
+ def rand_log_normal(shape, loc=0.0, scale=1.0, device="cpu", dtype=torch.float32):
313
+ """Draws samples from an lognormal distribution"""
314
+ u = stratified_with_settings(shape, device=device, dtype=dtype) * (1 - 2e-7) + 1e-7
315
+ return torch.distributions.Normal(loc, scale).icdf(u).exp()
316
+
317
+
318
+ def rand_log_logistic(shape, loc=0.0, scale=1.0, min_value=0.0, max_value=float("inf"), device="cpu", dtype=torch.float32):
319
+ """Draws samples from an optionally truncated log-logistic distribution"""
320
+ min_value = torch.as_tensor(min_value, device=device, dtype=torch.float64)
321
+ max_value = torch.as_tensor(max_value, device=device, dtype=torch.float64)
322
+ min_cdf = min_value.log().sub(loc).div(scale).sigmoid()
323
+ max_cdf = max_value.log().sub(loc).div(scale).sigmoid()
324
+ u = stratified_with_settings(shape, device=device, dtype=torch.float64) * (max_cdf - min_cdf) + min_cdf
325
+ return u.logit().mul(scale).add(loc).exp().to(dtype)
326
+
327
+
328
+ def rand_log_uniform(shape, min_value, max_value, device="cpu", dtype=torch.float32):
329
+ """Draws samples from an log-uniform distribution"""
330
+ min_value = math.log(min_value)
331
+ max_value = math.log(max_value)
332
+ return (stratified_with_settings(shape, device=device, dtype=dtype) * (max_value - min_value) + min_value).exp()
333
+
334
+
335
+ def rand_v_diffusion(shape, sigma_data=1.0, min_value=0.0, max_value=float("inf"), device="cpu", dtype=torch.float32):
336
+ """Draws samples from a truncated v-diffusion training timestep distribution"""
337
+ min_cdf = math.atan(min_value / sigma_data) * 2 / math.pi
338
+ max_cdf = math.atan(max_value / sigma_data) * 2 / math.pi
339
+ u = stratified_with_settings(shape, device=device, dtype=dtype) * (max_cdf - min_cdf) + min_cdf
340
+ return torch.tan(u * math.pi / 2) * sigma_data
341
+
342
+
343
+ def rand_cosine_interpolated(shape, image_d, noise_d_low, noise_d_high, sigma_data=1.0, min_value=1e-3, max_value=1e3, device="cpu", dtype=torch.float32):
344
+ """Draws samples from an interpolated cosine timestep distribution (from simple diffusion)"""
345
+
346
+ def logsnr_schedule_cosine(t, logsnr_min, logsnr_max):
347
+ t_min = math.atan(math.exp(-0.5 * logsnr_max))
348
+ t_max = math.atan(math.exp(-0.5 * logsnr_min))
349
+ return -2 * torch.log(torch.tan(t_min + t * (t_max - t_min)))
350
+
351
+ def logsnr_schedule_cosine_shifted(t, image_d, noise_d, logsnr_min, logsnr_max):
352
+ shift = 2 * math.log(noise_d / image_d)
353
+ return logsnr_schedule_cosine(t, logsnr_min - shift, logsnr_max - shift) + shift
354
+
355
+ def logsnr_schedule_cosine_interpolated(t, image_d, noise_d_low, noise_d_high, logsnr_min, logsnr_max):
356
+ logsnr_low = logsnr_schedule_cosine_shifted(t, image_d, noise_d_low, logsnr_min, logsnr_max)
357
+ logsnr_high = logsnr_schedule_cosine_shifted(t, image_d, noise_d_high, logsnr_min, logsnr_max)
358
+ return torch.lerp(logsnr_low, logsnr_high, t)
359
+
360
+ logsnr_min = -2 * math.log(min_value / sigma_data)
361
+ logsnr_max = -2 * math.log(max_value / sigma_data)
362
+ u = stratified_with_settings(shape, device=device, dtype=dtype)
363
+ logsnr = logsnr_schedule_cosine_interpolated(u, image_d, noise_d_low, noise_d_high, logsnr_min, logsnr_max)
364
+ return torch.exp(-logsnr / 2) * sigma_data
365
+
366
+
367
+ def rand_split_log_normal(shape, loc, scale_1, scale_2, device="cpu", dtype=torch.float32):
368
+ """Draws samples from a split lognormal distribution"""
369
+ n = torch.randn(shape, device=device, dtype=dtype).abs()
370
+ u = torch.rand(shape, device=device, dtype=dtype)
371
+ n_left = n * -scale_1 + loc
372
+ n_right = n * scale_2 + loc
373
+ ratio = scale_1 / (scale_1 + scale_2)
374
+ return torch.where(u < ratio, n_left, n_right).exp()
375
+
376
+
377
+ class FolderOfImages(data.Dataset):
378
+ """Recursively finds all images in a directory. It does not support
379
+ classes/targets"""
380
+
381
+ IMG_EXTENSIONS = {".jpg", ".jpeg", ".png", ".ppm", ".bmp", ".pgm", ".tif", ".tiff", ".webp"}
382
+
383
+ def __init__(self, root, transform=None):
384
+ super().__init__()
385
+ self.root = Path(root)
386
+ self.transform = nn.Identity() if transform is None else transform
387
+ self.paths = sorted(path for path in self.root.rglob("*") if path.suffix.lower() in self.IMG_EXTENSIONS)
388
+
389
+ def __repr__(self):
390
+ return f'FolderOfImages(root="{self.root}", len: {len(self)})'
391
+
392
+ def __len__(self):
393
+ return len(self.paths)
394
+
395
+ def __getitem__(self, key):
396
+ path = self.paths[key]
397
+ with open(path, "rb") as f:
398
+ image = Image.open(f).convert("RGB")
399
+ image = self.transform(image)
400
+ return (image,)
401
+
402
+
403
+ class CSVLogger:
404
+ def __init__(self, filename, columns):
405
+ self.filename = Path(filename)
406
+ self.columns = columns
407
+ if self.filename.exists():
408
+ self.file = open(self.filename, "a")
409
+ else:
410
+ self.file = open(self.filename, "w")
411
+ self.write(*self.columns)
412
+
413
+ def write(self, *args):
414
+ print(*args, sep=",", file=self.file, flush=True)
415
+
416
+
417
+ @contextmanager
418
+ def tf32_mode(cudnn=None, matmul=None):
419
+ """A context manager that sets whether TF32 is allowed on cuDNN or matmul"""
420
+ cudnn_old = torch.backends.cudnn.allow_tf32
421
+ matmul_old = torch.backends.cuda.matmul.allow_tf32
422
+ try:
423
+ if cudnn is not None:
424
+ torch.backends.cudnn.allow_tf32 = cudnn
425
+ if matmul is not None:
426
+ torch.backends.cuda.matmul.allow_tf32 = matmul
427
+ yield
428
+ finally:
429
+ if cudnn is not None:
430
+ torch.backends.cudnn.allow_tf32 = cudnn_old
431
+ if matmul is not None:
432
+ torch.backends.cuda.matmul.allow_tf32 = matmul_old
433
+
434
+
435
+ def get_safetensors_metadata(path):
436
+ """Retrieves the metadata from a safetensors file"""
437
+ return safetensors.safe_open(path, "pt").metadata()
438
+
439
+
440
+ def ema_update_dict(values, updates, decay):
441
+ for k, v in updates.items():
442
+ if k not in values:
443
+ values[k] = v
444
+ else:
445
+ values[k] *= decay
446
+ values[k] += (1 - decay) * v
447
+ return values
modules_forge/patch_basic.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import time
3
+ import warnings
4
+ from functools import wraps
5
+ from pathlib import Path
6
+
7
+ import gradio.networking
8
+ import httpx
9
+ import safetensors.torch
10
+ import torch
11
+ from tqdm import tqdm
12
+
13
+ from modules.errors import display
14
+
15
+
16
+ def gradio_url_ok_fix(url: str) -> bool:
17
+ try:
18
+ for _ in range(5):
19
+ with warnings.catch_warnings():
20
+ warnings.filterwarnings("ignore")
21
+ r = httpx.head(url, timeout=999, verify=False)
22
+ if r.status_code in (200, 401, 302):
23
+ return True
24
+ time.sleep(0.500)
25
+ except (ConnectionError, httpx.ConnectError):
26
+ return False
27
+ return False
28
+
29
+
30
+ def build_loaded(module, loader_name):
31
+ original_loader_name = f"{loader_name}_origin"
32
+
33
+ if not hasattr(module, original_loader_name):
34
+ setattr(module, original_loader_name, getattr(module, loader_name))
35
+
36
+ original_loader = getattr(module, original_loader_name)
37
+
38
+ @wraps(original_loader)
39
+ def loader(*args, **kwargs):
40
+ try:
41
+ with warnings.catch_warnings():
42
+ warnings.simplefilter(action="ignore", category=FutureWarning)
43
+ return original_loader(*args, **kwargs)
44
+ except Exception as e:
45
+ display(e, f"{module.__name__}.{loader_name}")
46
+
47
+ exc = "\n"
48
+ for path in list(args) + list(kwargs.values()):
49
+ if isinstance(path, str) and os.path.isfile(path):
50
+ exc += f'Failed to read file "{path}"\n'
51
+ backup_file = f"{path}.corrupted"
52
+ if os.path.exists(backup_file):
53
+ os.remove(backup_file)
54
+ os.replace(path, backup_file)
55
+ exc += f'Forge has moved the corrupted file to "{backup_file}"\n'
56
+ exc += "Please try downloading the model again\n"
57
+ print(exc)
58
+ raise ValueError from None
59
+
60
+ setattr(module, loader_name, loader)
61
+
62
+
63
+ def always_show_tqdm(*args, **kwargs):
64
+ kwargs["disable"] = False
65
+ if "name" in kwargs:
66
+ del kwargs["name"]
67
+ return tqdm(*args, **kwargs)
68
+
69
+
70
+ def long_path_prefix(path: Path) -> Path:
71
+ if os.name == "nt" and not str(path).startswith("\\\\?\\") and not path.exists():
72
+ return Path("\\\\?\\" + str(path))
73
+ return path
74
+
75
+
76
+ def patch_all_basics():
77
+ import logging
78
+
79
+ from huggingface_hub import file_download
80
+
81
+ file_download.tqdm = always_show_tqdm
82
+ file_download.logger.setLevel(logging.ERROR)
83
+
84
+ from huggingface_hub.file_download import _download_to_tmp_and_move as original_download_to_tmp_and_move
85
+
86
+ @wraps(original_download_to_tmp_and_move)
87
+ def patched_download_to_tmp_and_move(incomplete_path: Path, destination_path: Path, *args, **kwargs):
88
+ incomplete_path = long_path_prefix(incomplete_path)
89
+ destination_path = long_path_prefix(destination_path)
90
+ return original_download_to_tmp_and_move(incomplete_path, destination_path, *args, **kwargs)
91
+
92
+ file_download._download_to_tmp_and_move = patched_download_to_tmp_and_move
93
+
94
+ gradio.networking.url_ok = gradio_url_ok_fix
95
+ build_loaded(safetensors.torch, "load_file")
96
+ build_loaded(torch, "load")
modules_forge/presets.py ADDED
@@ -0,0 +1,148 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import TYPE_CHECKING, Callable
2
+
3
+ if TYPE_CHECKING:
4
+ from modules.options import OptionInfo
5
+
6
+ from enum import Enum
7
+
8
+ import gradio as gr
9
+
10
+ from backend.memory_management import total_vram
11
+ from modules.shared_items import list_samplers, list_schedulers
12
+
13
+
14
+ class PresetArch(Enum):
15
+ sd = 1
16
+ xl = 2
17
+ flux = 3
18
+ qwen = 4
19
+ lumina = 5
20
+ wan = 6
21
+
22
+
23
+ SAMPLERS = {
24
+ PresetArch.sd: "Euler a",
25
+ PresetArch.xl: "DPM++ 2M SDE",
26
+ PresetArch.flux: "Euler",
27
+ PresetArch.qwen: "LCM",
28
+ PresetArch.lumina: "Res Multistep",
29
+ PresetArch.wan: "Euler",
30
+ }
31
+
32
+ SCHEDULERS = {
33
+ PresetArch.sd: "Automatic",
34
+ PresetArch.xl: "Karras",
35
+ PresetArch.flux: "Beta",
36
+ PresetArch.qwen: "Normal",
37
+ PresetArch.lumina: "Linear Quadratic",
38
+ PresetArch.wan: "Simple",
39
+ }
40
+
41
+ WIDTH = {
42
+ PresetArch.sd: 512,
43
+ PresetArch.xl: 896,
44
+ PresetArch.flux: 896,
45
+ PresetArch.qwen: 896,
46
+ PresetArch.lumina: 1024,
47
+ PresetArch.wan: 1152,
48
+ }
49
+
50
+ HEIGHT = {
51
+ PresetArch.sd: 512,
52
+ PresetArch.xl: 1152,
53
+ PresetArch.flux: 1152,
54
+ PresetArch.qwen: 1152,
55
+ PresetArch.lumina: 1024,
56
+ PresetArch.wan: 896,
57
+ }
58
+
59
+ CFG = {
60
+ PresetArch.sd: 6.0,
61
+ PresetArch.xl: 4.0,
62
+ PresetArch.flux: 1.0,
63
+ PresetArch.qwen: 1.0,
64
+ PresetArch.lumina: 4.5,
65
+ PresetArch.wan: 1.0,
66
+ }
67
+
68
+
69
+ def register(options_templates: dict, options_section: Callable, OptionInfo: "OptionInfo"):
70
+ inference_vram = int(total_vram - (1024 if total_vram < 8200 else 2048))
71
+
72
+ for arch in PresetArch:
73
+ name = arch.name
74
+
75
+ options_templates.update(
76
+ options_section(
77
+ (None, "Forge Hidden Options"),
78
+ {
79
+ f"forge_checkpoint_{name}": OptionInfo(None),
80
+ f"forge_additional_modules_{name}": OptionInfo([]),
81
+ },
82
+ )
83
+ )
84
+
85
+ sampler, scheduler = SAMPLERS[arch], SCHEDULERS[arch]
86
+
87
+ options_templates.update(
88
+ options_section(
89
+ (f"ui_{name}", name.upper(), "presets"),
90
+ {
91
+ f"{name}_t2i_sampler": OptionInfo(sampler, "txt2img sampler", gr.Dropdown, lambda: {"choices": [x.name for x in list_samplers()]}),
92
+ f"{name}_t2i_scheduler": OptionInfo(scheduler, "txt2img scheduler", gr.Dropdown, lambda: {"choices": list_schedulers()}),
93
+ f"{name}_i2i_sampler": OptionInfo(sampler, "img2img sampler", gr.Dropdown, lambda: {"choices": [x.name for x in list_samplers()]}),
94
+ f"{name}_i2i_scheduler": OptionInfo(scheduler, "img2img scheduler", gr.Dropdown, lambda: {"choices": list_schedulers()}),
95
+ },
96
+ )
97
+ )
98
+
99
+ w, h, cfg = WIDTH[arch], HEIGHT[arch], CFG[arch]
100
+
101
+ options_templates.update(
102
+ options_section(
103
+ (f"ui_{name}", name.upper(), "presets"),
104
+ {
105
+ f"{name}_t2i_width": OptionInfo(w, "txt2img Width", gr.Slider, {"minimum": 64, "maximum": 2048, "step": 8}),
106
+ f"{name}_t2i_height": OptionInfo(h, "txt2img Height", gr.Slider, {"minimum": 64, "maximum": 2048, "step": 8}),
107
+ f"{name}_t2i_cfg": OptionInfo(cfg, "txt2img CFG", gr.Slider, {"minimum": 1, "maximum": 30, "step": 0.1}),
108
+ f"{name}_t2i_hr_cfg": OptionInfo(cfg, "txt2img Hires. CFG", gr.Slider, {"minimum": 1, "maximum": 30, "step": 0.1}),
109
+ f"{name}_i2i_width": OptionInfo(w, "img2img Width", gr.Slider, {"minimum": 64, "maximum": 2048, "step": 8}),
110
+ f"{name}_i2i_height": OptionInfo(h, "img2img Height", gr.Slider, {"minimum": 64, "maximum": 2048, "step": 8}),
111
+ f"{name}_i2i_cfg": OptionInfo(cfg, "img2img CFG", gr.Slider, {"minimum": 1, "maximum": 30, "step": 0.1}),
112
+ f"{name}_gpu_mb": OptionInfo(inference_vram, "GPU Weights (MB)", gr.Slider, {"visible": (arch is not PresetArch.sd), "minimum": 0, "maximum": total_vram, "step": 1}),
113
+ },
114
+ )
115
+ )
116
+
117
+ options_templates.update(
118
+ options_section(
119
+ ("ui_flux", "FLUX", "presets"),
120
+ {
121
+ "flux_t2i_d_cfg": OptionInfo(3.0, "txt2img Distilled CFG", gr.Slider, {"minimum": 1, "maximum": 10, "step": 0.1}),
122
+ "flux_t2i_hr_d_cfg": OptionInfo(3.0, "txt2img Distilled Hires. CFG", gr.Slider, {"minimum": 1, "maximum": 10, "step": 0.1}),
123
+ "flux_i2i_d_cfg": OptionInfo(3.0, "img2img Distilled CFG", gr.Slider, {"minimum": 1, "maximum": 10, "step": 0.1}),
124
+ },
125
+ )
126
+ )
127
+
128
+ options_templates.update(
129
+ options_section(
130
+ ("ui_lumina", "LUMINA", "presets"),
131
+ {
132
+ "lumina_t2i_d_cfg": OptionInfo(6.0, "txt2img Shift", gr.Slider, {"minimum": 1, "maximum": 10, "step": 0.1}),
133
+ "lumina_t2i_hr_d_cfg": OptionInfo(6.0, "txt2img Hires. Shift", gr.Slider, {"minimum": 1, "maximum": 10, "step": 0.1}),
134
+ "lumina_i2i_d_cfg": OptionInfo(6.0, "img2img Shift", gr.Slider, {"minimum": 1, "maximum": 10, "step": 0.1}),
135
+ },
136
+ )
137
+ )
138
+
139
+ options_templates.update(
140
+ options_section(
141
+ ("ui_wan", "WAN", "presets"),
142
+ {
143
+ "wan_t2i_d_cfg": OptionInfo(8.0, "txt2img Shift", gr.Slider, {"minimum": 1, "maximum": 10, "step": 0.1}),
144
+ "wan_t2i_hr_d_cfg": OptionInfo(8.0, "txt2img Hires. Shift", gr.Slider, {"minimum": 1, "maximum": 10, "step": 0.1}),
145
+ "wan_i2i_d_cfg": OptionInfo(8.0, "img2img Shift", gr.Slider, {"minimum": 1, "maximum": 10, "step": 0.1}),
146
+ },
147
+ )
148
+ )