char-fork/llama.cpp
git clone https://git.t4t.associates/char-fork/llama.cpp
9a7570587
char/aliceai-t5-moe
1from __future__import annotations 2 3import logging 4import os 5import shutil 6import struct 7import sys 8import tempfile 9from dataclasses import dataclass 10from enum import Enum ,auto 11from math import prod 12from pathlib import Path 13from io import BufferedWriter 14from typing import IO ,Any ,Sequence ,Mapping 15from string import ascii_letters ,digits 16 17import numpy as np 18 19from .constants import ( 20GGUF_DEFAULT_ALIGNMENT , 21GGUF_MAGIC , 22GGUF_VERSION , 23GGMLQuantizationType , 24GGUFEndian , 25GGUFValueType , 26Keys , 27RopeScalingType , 28PoolingType , 29TokenType , 30ExpertGatingFuncType , 31) 32 33from .quants import quant_shape_from_byte_shape 34 35logger = logging .getLogger (__name__ ) 36 37 38SHARD_NAME_FORMAT = "{:s}-{:05d}-of-{:05d}.gguf" 39 40 41@dataclass 42class TensorInfo : 43shape :Sequence [int ] 44dtype :GGMLQuantizationType 45nbytes :int 46tensor :np .ndarray [Any ,Any ]| None = None 47 48 49@dataclass 50class GGUFValue : 51value :Any 52type :GGUFValueType 53sub_type :GGUFValueType | None = None 54 55 56class WriterState (Enum ): 57NO_FILE = auto () 58EMPTY = auto () 59HEADER = auto () 60KV_DATA = auto () 61TI_DATA = auto () 62WEIGHTS = auto () 63 64 65class GGUFWriter : 66fout :list [BufferedWriter ]| None 67path :Path | None 68temp_file :tempfile .SpooledTemporaryFile [bytes ]| None 69tensors :list [dict [str ,TensorInfo ]] 70kv_data :list [dict [str ,GGUFValue ]] 71state :WriterState 72_simple_value_packing = { 73GGUFValueType .UINT8 :"B" , 74GGUFValueType .INT8 :"b" , 75GGUFValueType .UINT16 :"H" , 76GGUFValueType .INT16 :"h" , 77GGUFValueType .UINT32 :"I" , 78GGUFValueType .INT32 :"i" , 79GGUFValueType .FLOAT32 :"f" , 80GGUFValueType .UINT64 :"Q" , 81GGUFValueType .INT64 :"q" , 82GGUFValueType .FLOAT64 :"d" , 83GGUFValueType .BOOL :"?" , 84 } 85 86def __init__ ( 87self ,path :os .PathLike [str ]| str | None ,arch :str ,use_temp_file :bool = False ,endianess :GGUFEndian = GGUFEndian .LITTLE , 88split_max_tensors :int = 0 ,split_max_size :int = 0 ,dry_run :bool = False ,small_first_shard :bool = False 89 ): 90self .fout = None 91self .path = Path (path )if path else None 92self .arch = arch 93self .endianess = endianess 94self .data_alignment = GGUF_DEFAULT_ALIGNMENT 95self .use_temp_file = use_temp_file 96self .temp_file = None 97self .tensors = [{}] 98self .kv_data = [{}] 99self .split_max_tensors = split_max_tensors 100self .split_max_size = split_max_size 101self .dry_run = dry_run 102self .small_first_shard = small_first_shard 103logger .info ("gguf: This GGUF file is for {0} Endian only" .format ( 104"Big" if self .endianess == GGUFEndian .BIG else "Little" , 105 )) 106self .state = WriterState .NO_FILE 107 108if self .small_first_shard : 109self .tensors .append ({}) 110 111self .add_architecture () 112 113def get_total_parameter_count (self )-> tuple [int ,int ,int ,int ]: 114total_params = 0 115shared_params = 0 116expert_params = 0 117 118expert_sum = 0 119n_expert_tensors = 0 120 121last_lora_a :tuple [str ,TensorInfo ]| None = None 122 123for tensors in self .tensors : 124for name ,info in tensors .items (): 125 126shape = info .shape 127 128if name .endswith (".lora_a" ): 129last_lora_a = (name ,info ) 130continue 131elif name .endswith (".lora_b" ): 132if last_lora_a is None or last_lora_a [0 ]!= name [:- 1 ]+ "a" : 133# Bail when the LoRA pair can't be found trivially 134logger .warning ("can't measure LoRA size correctly, tensor order is unusual" ) 135return 0 ,0 ,0 ,0 136else : 137shape = (* shape [:- 1 ],last_lora_a [1 ].shape [- 1 ]) 138 139size = prod (shape ) 140 141if "_exps." in name : 142if len (shape )>= 3 : 143expert_count = shape [- 2 if ".bias" in name else - 3 ] 144expert_params += (size // expert_count ) 145expert_sum += expert_count 146n_expert_tensors += 1 147else : 148shared_params += size 149else : 150shared_params += size 151 152total_params += size 153 154# Hopefully this should work even for variable-expert-count models 155expert_count = (expert_sum // n_expert_tensors )if n_expert_tensors > 0 else 0 156 157# Negate the total to signal it's likely not exact 158if last_lora_a is not None : 159total_params = - total_params 160 161# NOTE: keep the output in the same order as accepted by 'size_label' in gguf-py/gguf/utility.py 162return total_params ,shared_params ,expert_params ,expert_count 163 164def format_shard_names (self ,path :Path )-> list [Path ]: 165if len (self .tensors )== 1 : 166return [path ] 167return [path .with_name (SHARD_NAME_FORMAT .format (path .stem ,i + 1 ,len (self .tensors )))for i in range (len (self .tensors ))] 168 169def open_output_file (self ,path :Path | None = None )-> None : 170if self .state is WriterState .EMPTY and self .fout is not None and (path is None or path == self .path ): 171# allow calling this multiple times as long as the path is the same 172return 173 174if self .state is not WriterState .NO_FILE : 175raise ValueError (f'Expected output file to be not yet opened, got { self . state } ' ) 176 177if path is not None : 178self .path = path 179 180if self .path is not None : 181filenames = self .print_plan () 182self .fout = [open (filename ,"wb" )for filename in filenames ] 183self .state = WriterState .EMPTY 184 185def print_plan (self )-> list [Path ]: 186logger .info ("Writing the following files:" ) 187assert self .path is not None 188filenames = self .format_shard_names (self .path ) 189assert len (filenames )== len (self .tensors ) 190for name ,tensors in zip (filenames ,self .tensors ): 191logger .info (f" { name } : n_tensors = { len ( tensors ) } , total_size = { GGUFWriter . format_n_bytes_to_str ( sum ( ti . nbytes for ti in tensors . values ())) } " ) 192 193if self .dry_run : 194logger .info ("Dry run, not writing files" ) 195for name in filenames : 196name )# noqa: NP100 197exit () 198 199return filenames 200 201def add_shard_kv_data (self )-> None : 202if len (self .tensors )== 1 : 203return 204 205total_tensors = sum (len (t )for t in self .tensors ) 206assert self .fout is not None 207total_splits = len (self .fout ) 208self .kv_data .extend ({}for _ in range (len (self .kv_data ),total_splits )) 209for i ,kv_data in enumerate (self .kv_data ): 210kv_data [Keys .Split .LLM_KV_SPLIT_NO ]= GGUFValue (i ,GGUFValueType .UINT16 ) 211kv_data [Keys .Split .LLM_KV_SPLIT_COUNT ]= GGUFValue (total_splits ,GGUFValueType .UINT16 ) 212kv_data [Keys .Split .LLM_KV_SPLIT_TENSORS_COUNT ]= GGUFValue (total_tensors ,GGUFValueType .INT32 ) 213 214def write_header_to_file (self ,path :Path | None = None )-> None : 215if len (self .tensors )== 1 and (self .split_max_tensors != 0 or self .split_max_size != 0 ): 216logger .warning ("Model fails split requirements, not splitting" ) 217 218self .open_output_file (path ) 219 220if self .state is not WriterState .EMPTY : 221raise ValueError (f'Expected output file to be empty, got { self . state } ' ) 222 223assert self .fout is not None 224assert len (self .fout )== len (self .tensors ) 225assert len (self .kv_data )== 1 226 227self .add_shard_kv_data () 228 229for fout ,tensors ,kv_data in zip (self .fout ,self .tensors ,self .kv_data ): 230fout .write (self ._pack ("<I" ,GGUF_MAGIC ,skip_pack_prefix = True )) 231fout .write (self ._pack ("I" ,GGUF_VERSION )) 232fout .write (self ._pack ("Q" ,len (tensors ))) 233fout .write (self ._pack ("Q" ,len (kv_data ))) 234fout .flush () 235self .state = WriterState .HEADER 236 237def write_kv_data_to_file (self )-> None : 238if self .state is not WriterState .HEADER : 239raise ValueError (f'Expected output file to contain the header, got { self . state } ' ) 240assert self .fout is not None 241 242for fout ,kv_data in zip (self .fout ,self .kv_data ): 243kv_bytes = bytearray () 244 245for key ,val in kv_data .items (): 246kv_bytes += self ._pack_val (key ,GGUFValueType .STRING ,add_vtype = False ) 247kv_bytes += self ._pack_val (val .value ,val .type ,add_vtype = True ,sub_type = val .sub_type ) 248 249fout .write (kv_bytes ) 250 251self .flush () 252self .state = WriterState .KV_DATA 253 254def write_ti_data_to_file (self )-> None : 255if self .state is not WriterState .KV_DATA : 256raise ValueError (f'Expected output file to contain KV data, got { self . state } ' ) 257assert self .fout is not None 258 259for fout ,tensors in zip (self .fout ,self .tensors ): 260ti_data = bytearray () 261offset_tensor = 0 262 263for name ,ti in tensors .items (): 264ti_data += self ._pack_val (name ,GGUFValueType .STRING ,add_vtype = False ) 265n_dims = len (ti .shape ) 266ti_data += self ._pack ("I" ,n_dims ) 267for j in range (n_dims ): 268ti_data += self ._pack ("Q" ,ti .shape [n_dims - 1 - j ]) 269ti_data += self ._pack ("I" ,ti .dtype ) 270ti_data += self ._pack ("Q" ,offset_tensor ) 271offset_tensor += GGUFWriter .ggml_pad (ti .nbytes ,self .data_alignment ) 272 273fout .write (ti_data ) 274fout .flush () 275self .state = WriterState .TI_DATA 276 277def add_key_value (self ,key :str ,val :Any ,vtype :GGUFValueType ,sub_type :GGUFValueType | None = None )-> None : 278if any (key in kv_data for kv_data in self .kv_data ): 279logger .warning (f'Duplicated key name { key !r } , overwriting it with new value { val !r } of type { vtype . name } ' ) 280 281self .kv_data [0 ][key ]= GGUFValue (value = val ,type = vtype ,sub_type = sub_type ) 282 283def remove_key (self ,key :str )-> None : 284for kv_data in self .kv_data : 285kv_data .pop (key ,None ) 286 287def add_uint8 (self ,key :str ,val :int )-> None : 288self .add_key_value (key ,val ,GGUFValueType .UINT8 ) 289 290def add_int8 (self ,key :str ,val :int )-> None : 291self .add_key_value (key ,val ,GGUFValueType .INT8 ) 292 293def add_uint16 (self ,key :str ,val :int )-> None : 294self .add_key_value (key ,val ,GGUFValueType .UINT16 ) 295 296def add_int16 (self ,key :str ,val :int )-> None : 297self .add_key_value (key ,val ,GGUFValueType .INT16 ) 298 299def add_uint32 (self ,key :str ,val :int )-> None : 300self .add_key_value (key ,val ,GGUFValueType .UINT32 ) 301 302def add_int32 (self ,key :str ,val :int )-> None : 303self .add_key_value (key ,val ,GGUFValueType .INT32 ) 304 305def add_float32 (self ,key :str ,val :float )-> None : 306self .add_key_value (key ,val ,GGUFValueType .FLOAT32 ) 307 308def add_uint64 (self ,key :str ,val :int )-> None : 309self .add_key_value (key ,val ,GGUFValueType .UINT64 ) 310 311def add_int64 (self ,key :str ,val :int )-> None : 312self .add_key_value (key ,val ,GGUFValueType .INT64 ) 313 314def add_float64 (self ,key :str ,val :float )-> None : 315self .add_key_value (key ,val ,GGUFValueType .FLOAT64 ) 316 317def add_bool (self ,key :str ,val :bool )-> None : 318self .add_key_value (key ,val ,GGUFValueType .BOOL ) 319 320def add_string (self ,key :str ,val :str )-> None : 321if not val : 322return 323self .add_key_value (key ,val ,GGUFValueType .STRING ) 324 325def add_array (self ,key :str ,val :Sequence [Any ])-> None : 326if len (val )== 0 : 327return 328self .add_key_value (key ,val ,GGUFValueType .ARRAY ) 329 330@staticmethod 331def ggml_pad (x :int ,n :int )-> int : 332return ((x + n - 1 )// n )* n 333 334def add_tensor_info ( 335self ,name :str ,tensor_shape :Sequence [int ],tensor_dtype :np .dtype , 336tensor_nbytes :int ,raw_dtype :GGMLQuantizationType | None = None , 337 )-> None : 338if self .state is not WriterState .NO_FILE : 339raise ValueError (f'Expected output file to be not yet opened, got { self . state } ' ) 340 341if any (name in tensors for tensors in self .tensors ): 342raise ValueError (f'Duplicated tensor name { name !r } ' ) 343 344if raw_dtype is None : 345if tensor_dtype == np .float16 : 346dtype = GGMLQuantizationType .F16 347elif tensor_dtype == np .float32 : 348dtype = GGMLQuantizationType .F32 349elif tensor_dtype == np .float64 : 350dtype = GGMLQuantizationType .F64 351elif tensor_dtype == np .int8 : 352dtype = GGMLQuantizationType .I8 353elif tensor_dtype == np .int16 : 354dtype = GGMLQuantizationType .I16 355elif tensor_dtype == np .int32 : 356dtype = GGMLQuantizationType .I32 357elif tensor_dtype == np .int64 : 358dtype = GGMLQuantizationType .I64 359else : 360raise ValueError ("Only F16, F32, F64, I8, I16, I32, I64 tensors are supported for now" ) 361else : 362dtype = raw_dtype 363if tensor_dtype == np .uint8 : 364tensor_shape = quant_shape_from_byte_shape (tensor_shape ,raw_dtype ) 365 366# make sure there is at least one tensor before splitting 367if len (self .tensors [- 1 ])> 0 : 368if (# split when over tensor limit 369self .split_max_tensors != 0 370and len (self .tensors [- 1 ])>= self .split_max_tensors 371 )or (# split when over size limit 372self .split_max_size != 0 373and sum (ti .nbytes for ti in self .tensors [- 1 ].values ())+ tensor_nbytes > self .split_max_size 374 ): 375self .tensors .append ({}) 376 377self .tensors [- 1 ][name ]= TensorInfo (shape = tensor_shape ,dtype = dtype ,nbytes = tensor_nbytes ) 378 379def add_tensor ( 380self ,name :str ,tensor :np .ndarray [Any ,Any ],raw_shape :Sequence [int ]| None = None , 381raw_dtype :GGMLQuantizationType | None = None ,tensor_endianess :GGUFEndian | None = None 382 )-> None : 383# if tensor endianness is not passed, assume it's native to system 384if tensor_endianess is None : 385tensor_endianess = GGUFEndian .BIG if sys .byteorder == 'big' else GGUFEndian .LITTLE 386 387if tensor_endianess != self .endianess : 388# Don't byteswap inplace since lazy copies cannot handle it 389tensor = tensor .byteswap (inplace = False ) 390if self .use_temp_file and self .temp_file is None : 391fp = tempfile .SpooledTemporaryFile (mode = "w+b" ,max_size = 256 * 1024 * 1024 ) 392fp .seek (0 ) 393self .temp_file = fp 394 395shape :Sequence [int ]= raw_shape if raw_shape is not None else tensor .shape 396self .add_tensor_info (name ,shape ,tensor .dtype ,tensor .nbytes ,raw_dtype = raw_dtype ) 397 398if self .temp_file is None : 399self .tensors [- 1 ][name ].tensor = tensor 400return 401 402tensor .tofile (self .temp_file ) 403self .write_padding (self .temp_file ,tensor .nbytes ) 404 405def write_padding (self ,fp :IO [bytes ],n :int ,align :int | None = None )-> None : 406pad = GGUFWriter .ggml_pad (n ,align if align is not None else self .data_alignment )- n 407if pad != 0 : 408fp .write (bytes ([0 ]* pad )) 409 410def write_tensor_data (self ,tensor :np .ndarray [Any ,Any ],tensor_endianess :GGUFEndian | None = None )-> None : 411if self .state is not WriterState .TI_DATA and self .state is not WriterState .WEIGHTS : 412raise ValueError (f'Expected output file to contain tensor info or weights, got { self . state } ' ) 413assert self .fout is not None 414 415# if tensor endianness is not passed, assume it's native to system 416if tensor_endianess is None : 417tensor_endianess = GGUFEndian .BIG if sys .byteorder == 'big' else GGUFEndian .LITTLE 418 419if tensor_endianess != self .endianess : 420# Don't byteswap inplace since lazy copies cannot handle it 421tensor = tensor .byteswap (inplace = False ) 422 423file_id = - 1 424for i ,tensors in enumerate (self .tensors ): 425if len (tensors )> 0 : 426file_id = i 427break 428 429fout = self .fout [file_id ] 430 431# pop the first tensor info 432first_tensor_name = next (iter (self .tensors [file_id ])) 433ti = self .tensors [file_id ].pop (first_tensor_name ) 434assert ti .nbytes == tensor .nbytes 435 436self .write_padding (fout ,fout .tell ()) 437tensor .tofile (fout ) 438self .write_padding (fout ,tensor .nbytes ) 439 440self .state = WriterState .WEIGHTS 441 442def write_tensors_to_file (self ,* ,progress :bool = False )-> None : 443self .write_ti_data_to_file () 444 445assert self .fout is not None 446 447for fout in self .fout : 448self .write_padding (fout ,fout .tell ()) 449 450if self .temp_file is None : 451shard_bar = None 452bar = None 453 454if progress : 455from tqdm import tqdm 456 457total_bytes = sum (ti .nbytes for t in self .tensors for ti in t .values ()) 458 459if len (self .fout )> 1 : 460shard_bar = tqdm (desc = f"Shard (0/ { len ( self . fout ) } )" ,total = None ,unit = "byte" ,unit_scale = True ) 461bar = tqdm (desc = "Writing" ,total = total_bytes ,unit = "byte" ,unit_scale = True ) 462 463for i , (fout ,tensors )in enumerate (zip (self .fout ,self .tensors )): 464if shard_bar is not None : 465shard_bar .set_description (f"Shard ( { i + 1 } / { len ( self . fout ) } )" ) 466total = sum (ti .nbytes for ti in tensors .values ()) 467shard_bar .reset (total = (total if total > 0 else None )) 468 469# relying on the fact that Python dicts preserve insertion order (since 3.7) 470for name ,ti in tensors .items (): 471assert ti .tensor is not None # can only iterate once over the tensors 472assert ti .tensor .nbytes == ti .nbytes 473start = fout .tell () 474ti .tensor .tofile (fout ) 475# a short write here would only surface as a corrupt file at load time 476if fout .tell ()- start != ti .nbytes : 477raise ValueError ( 478f"tensor { name !r } wrote { fout . tell () - start } bytes, expected { ti . nbytes } " ) 479if shard_bar is not None : 480shard_bar .update (ti .nbytes ) 481if bar is not None : 482bar .update (ti .nbytes ) 483self .write_padding (fout ,ti .nbytes ) 484ti .tensor = None 485else : 486self .temp_file .seek (0 ) 487 488shutil .copyfileobj (self .temp_file ,self .fout [0 if not self .small_first_shard else 1 ]) 489self .flush () 490self .temp_file .close () 491 492self .state = WriterState .WEIGHTS 493 494def flush (self )-> None : 495assert self .fout is not None 496for fout in self .fout : 497fout .flush () 498 499def close (self )-> None : 500if self .fout is not None : 501for fout in self .fout : 502fout .close () 503self .fout = None 504 505def add_type (self ,type_name :str )-> None : 506self .add_string (Keys .General .TYPE ,type_name ) 507 508def add_architecture (self )-> None : 509self .add_string (Keys .General .ARCHITECTURE ,self .arch ) 510 511def add_quantization_version (self ,quantization_version :int )-> None : 512self .add_uint32 (Keys .General .QUANTIZATION_VERSION ,quantization_version ) 513 514def add_custom_alignment (self ,alignment :int )-> None : 515if alignment <= 0 or (alignment & (alignment - 1 ))!= 0 : 516raise ValueError ('Invalid alignment: must be a non-zero power of two' ) 517self .data_alignment = alignment 518self .add_uint32 (Keys .General .ALIGNMENT ,alignment ) 519 520def add_file_type (self ,ftype :int )-> None : 521self .add_uint32 (Keys .General .FILE_TYPE ,ftype ) 522 523def add_sampling_sequence (self ,sequence :str )-> None : 524self .add_string (Keys .General .SAMPLING_SEQUENCE ,sequence ) 525 526def add_sampling_top_k (self ,top_k :int )-> None : 527self .add_int32 (Keys .General .SAMPLING_TOP_K ,top_k ) 528 529def add_sampling_top_p (self ,top_p :float )-> None : 530self .add_float32 (Keys .General .SAMPLING_TOP_P ,top_p ) 531 532def add_sampling_min_p (self ,min_p :float )-> None : 533self .add_float32 (Keys .General .SAMPLING_MIN_P ,min_p ) 534 535def add_sampling_xtc_probability (self ,xtc_probability :float )-> None : 536self .add_float32 (Keys .General .SAMPLING_XTC_PROBABILITY ,xtc_probability ) 537 538def add_sampling_xtc_threshold (self ,xtc_threshold :float )-> None : 539self .add_float32 (Keys .General .SAMPLING_XTC_THRESHOLD ,xtc_threshold ) 540 541def add_sampling_temp (self ,temp :float )-> None : 542self .add_float32 (Keys .General .SAMPLING_TEMP ,temp ) 543 544def add_sampling_penalty_last_n (self ,penalty_last_n :int )-> None : 545self .add_int32 (Keys .General .SAMPLING_PENALTY_LAST_N ,penalty_last_n ) 546 547def add_sampling_penalty_repeat (self ,penalty_repeat :float )-> None : 548self .add_float32 (Keys .General .SAMPLING_PENALTY_REPEAT ,penalty_repeat ) 549 550def add_sampling_mirostat (self ,mirostat :int )-> None : 551self .add_int32 (Keys .General .SAMPLING_MIROSTAT ,mirostat ) 552 553def add_sampling_mirostat_tau (self ,mirostat_tau :float )-> None : 554self .add_float32 (Keys .General .SAMPLING_MIROSTAT_TAU ,mirostat_tau ) 555 556def add_sampling_mirostat_eta (self ,mirostat_eta :float )-> None : 557self .add_float32 (Keys .General .SAMPLING_MIROSTAT_ETA ,mirostat_eta ) 558 559def add_name (self ,name :str )-> None : 560self .add_string (Keys .General .NAME ,name ) 561 562def add_author (self ,author :str )-> None : 563self .add_string (Keys .General .AUTHOR ,author ) 564 565def add_version (self ,version :str )-> None : 566self .add_string (Keys .General .VERSION ,version ) 567 568def add_organization (self ,organization :str )-> None : 569self .add_string (Keys .General .ORGANIZATION ,organization ) 570 571def add_finetune (self ,finetune :str )-> None : 572self .add_string (Keys .General .FINETUNE ,finetune ) 573 574def add_basename (self ,basename :str )-> None : 575self .add_string (Keys .General .BASENAME ,basename ) 576 577def add_description (self ,description :str )-> None : 578self .add_string (Keys .General .DESCRIPTION ,description ) 579 580def add_quantized_by (self ,quantized :str )-> None : 581self .add_string (Keys .General .QUANTIZED_BY ,quantized ) 582 583def add_size_label (self ,size_label :str )-> None : 584self .add_string (Keys .General .SIZE_LABEL ,size_label ) 585 586def add_license (self ,license :str )-> None : 587self .add_string (Keys .General .LICENSE ,license ) 588 589def add_license_name (self ,license :str )-> None : 590self .add_string (Keys .General .LICENSE_NAME ,license ) 591 592def add_license_link (self ,license :str )-> None : 593self .add_string (Keys .General .LICENSE_LINK ,license ) 594 595def add_url (self ,url :str )-> None : 596self .add_string (Keys .General .URL ,url ) 597 598def add_doi (self ,doi :str )-> None : 599self .add_string (Keys .General .DOI ,doi ) 600 601def add_uuid (self ,uuid :str )-> None : 602self .add_string (Keys .General .UUID ,uuid ) 603 604def add_repo_url (self ,repo_url :str )-> None : 605self .add_string (Keys .General .REPO_URL ,repo_url ) 606 607def add_source_url (self ,url :str )-> None : 608self .add_string (Keys .General .SOURCE_URL ,url ) 609 610def add_source_doi (self ,doi :str )-> None : 611self .add_string (Keys .General .SOURCE_DOI ,doi ) 612 613def add_source_uuid (self ,uuid :str )-> None : 614self .add_string (Keys .General .SOURCE_UUID ,uuid ) 615 616def add_source_repo_url (self ,repo_url :str )-> None : 617self .add_string (Keys .General .SOURCE_REPO_URL ,repo_url ) 618 619def add_base_model_count (self ,source_count :int )-> None : 620self .add_uint32 (Keys .General .BASE_MODEL_COUNT ,source_count ) 621 622def add_base_model_name (self ,source_id :int ,name :str )-> None : 623self .add_string (Keys .General .BASE_MODEL_NAME .format (id = source_id ),name ) 624 625def add_base_model_author (self ,source_id :int ,author :str )-> None : 626self .add_string (Keys .General .BASE_MODEL_AUTHOR .format (id = source_id ),author ) 627 628def add_base_model_version (self ,source_id :int ,version :str )-> None : 629self .add_string (Keys .General .BASE_MODEL_VERSION .format (id = source_id ),version ) 630 631def add_base_model_organization (self ,source_id :int ,organization :str )-> None : 632self .add_string (Keys .General .BASE_MODEL_ORGANIZATION .format (id = source_id ),organization ) 633 634def add_base_model_description (self ,source_id :int ,description :str )-> None : 635self .add_string (Keys .General .BASE_MODEL_DESCRIPTION .format (id = source_id ),description ) 636 637def add_base_model_url (self ,source_id :int ,url :str )-> None : 638self .add_string (Keys .General .BASE_MODEL_URL .format (id = source_id ),url ) 639 640def add_base_model_doi (self ,source_id :int ,doi :str )-> None : 641self .add_string (Keys .General .BASE_MODEL_DOI .format (id = source_id ),doi ) 642 643def add_base_model_uuid (self ,source_id :int ,uuid :str )-> None : 644self .add_string (Keys .General .BASE_MODEL_UUID .format (id = source_id ),uuid ) 645 646def add_base_model_repo_url (self ,source_id :int ,repo_url :str )-> None : 647self .add_string (Keys .General .BASE_MODEL_REPO_URL .format (id = source_id ),repo_url ) 648 649def add_dataset_count (self ,source_count :int )-> None : 650self .add_uint32 (Keys .General .DATASET_COUNT ,source_count ) 651 652def add_dataset_name (self ,source_id :int ,name :str )-> None : 653self .add_string (Keys .General .DATASET_NAME .format (id = source_id ),name ) 654 655def add_dataset_author (self ,source_id :int ,author :str )-> None : 656self .add_string (Keys .General .DATASET_AUTHOR .format (id = source_id ),author ) 657 658def add_dataset_version (self ,source_id :int ,version :str )-> None : 659self .add_string (Keys .General .DATASET_VERSION .format (id = source_id ),version ) 660 661def add_dataset_organization (self ,source_id :int ,organization :str )-> None : 662self .add_string (Keys .General .DATASET_ORGANIZATION .format (id = source_id ),organization ) 663 664def add_dataset_description (self ,source_id :int ,description :str )-> None : 665self .add_string (Keys .General .DATASET_DESCRIPTION .format (id = source_id ),description ) 666 667def add_dataset_url (self ,source_id :int ,url :str )-> None : 668self .add_string (Keys .General .DATASET_URL .format (id = source_id ),url ) 669 670def add_dataset_doi (self ,source_id :int ,doi :str )-> None : 671self .add_string (Keys .General .DATASET_DOI .format (id = source_id ),doi ) 672 673def add_dataset_uuid (self ,source_id :int ,uuid :str )-> None : 674self .add_string (Keys .General .DATASET_UUID .format (id = source_id ),uuid ) 675 676def add_dataset_repo_url (self ,source_id :int ,repo_url :str )-> None : 677self .add_string (Keys .General .DATASET_REPO_URL .format (id = source_id ),repo_url ) 678 679def add_tags (self ,tags :Sequence [str ])-> None : 680self .add_array (Keys .General .TAGS ,tags ) 681 682def add_languages (self ,languages :Sequence [str ])-> None : 683self .add_array (Keys .General .LANGUAGES ,languages ) 684 685def add_tensor_data_layout (self ,layout :str )-> None : 686self .add_string (Keys .LLM .TENSOR_DATA_LAYOUT .format (arch = self .arch ),layout ) 687 688def add_vocab_size (self ,size :int )-> None : 689self .add_uint32 (Keys .LLM .VOCAB_SIZE .format (arch = self .arch ),size ) 690 691def add_context_length (self ,length :int )-> None : 692self .add_uint32 (Keys .LLM .CONTEXT_LENGTH .format (arch = self .arch ),length ) 693 694def add_embedding_length (self ,length :int )-> None : 695self .add_uint32 (Keys .LLM .EMBEDDING_LENGTH .format (arch = self .arch ),length ) 696 697def add_embedding_length_out (self ,length :int )-> None : 698self .add_uint32 (Keys .LLM .EMBEDDING_LENGTH_OUT .format (arch = self .arch ),length ) 699 700def add_features_length (self ,length :int )-> None : 701self .add_uint32 (Keys .LLM .FEATURES_LENGTH .format (arch = self .arch ),length ) 702 703def add_posnet_embedding_length (self ,length :int )-> None : 704self .add_uint32 (Keys .PosNet .EMBEDDING_LENGTH .format (arch = self .arch ),length ) 705 706def add_posnet_block_count (self ,length :int )-> None : 707self .add_uint32 (Keys .PosNet .BLOCK_COUNT .format (arch = self .arch ),length ) 708 709def add_convnext_embedding_length (self ,length :int )-> None : 710self .add_uint32 (Keys .ConvNext .EMBEDDING_LENGTH .format (arch = self .arch ),length ) 711 712def add_convnext_block_count (self ,length :int )-> None : 713self .add_uint32 (Keys .ConvNext .BLOCK_COUNT .format (arch = self .arch ),length ) 714 715def add_shortconv_l_cache (self ,length :int )-> None : 716self .add_uint32 (Keys .ShortConv .L_CACHE .format (arch = self .arch ),length ) 717 718def add_block_count (self ,length :int )-> None : 719self .add_uint32 (Keys .LLM .BLOCK_COUNT .format (arch = self .arch ),length ) 720 721def add_leading_dense_block_count (self ,length :int )-> None : 722self .add_uint32 (Keys .LLM .LEADING_DENSE_BLOCK_COUNT .format (arch = self .arch ),length ) 723 724def add_full_attention_interval (self ,interval :int )-> None : 725self .add_uint32 (Keys .LLM .FULL_ATTENTION_INTERVAL .format (arch = self .arch ),interval ) 726 727def add_hash_layer_count (self ,count :int )-> None : 728self .add_uint32 (Keys .LLM .HASH_LAYER_COUNT .format (arch = self .arch ),count ) 729 730def add_feed_forward_length (self ,length :int | Sequence [int ])-> None : 731if isinstance (length ,int ): 732self .add_uint32 (Keys .LLM .FEED_FORWARD_LENGTH .format (arch = self .arch ),length ) 733else : 734self .add_array (Keys .LLM .FEED_FORWARD_LENGTH .format (arch = self .arch ),length ) 735 736def add_expert_feed_forward_length (self ,length :int | Sequence [int ])-> None : 737if isinstance (length ,int ): 738self .add_uint32 (Keys .LLM .EXPERT_FEED_FORWARD_LENGTH .format (arch = self .arch ),length ) 739else : 740self .add_array (Keys .LLM .EXPERT_FEED_FORWARD_LENGTH .format (arch = self .arch ),length ) 741 742def add_expert_shared_feed_forward_length (self ,length :int )-> None : 743self .add_uint32 (Keys .LLM .EXPERT_SHARED_FEED_FORWARD_LENGTH .format (arch = self .arch ),length ) 744 745def add_expert_chunk_feed_forward_length (self ,length :int )-> None : 746self .add_uint32 (Keys .LLM .EXPERT_CHUNK_FEED_FORWARD_LENGTH .format (arch = self .arch ),length ) 747 748def add_parallel_residual (self ,use :bool )-> None : 749self .add_bool (Keys .LLM .USE_PARALLEL_RESIDUAL .format (arch = self .arch ),use ) 750 751def add_decoder_start_token_id (self ,id :int )-> None : 752self .add_uint32 (Keys .LLM .DECODER_START_TOKEN_ID .format (arch = self .arch ),id ) 753 754def add_decoder_block_count (self ,value :int )-> None : 755self .add_uint32 (Keys .LLM .DECODER_BLOCK_COUNT .format (arch = self .arch ),value ) 756 757def add_embedding_length_per_layer_input (self ,value :int )-> None : 758self .add_uint32 (Keys .LLM .EMBD_LENGTH_PER_LAYER_INP .format (arch = self .arch ),value ) 759 760def add_altup_active_idx (self ,val :int )-> None : 761self .add_uint32 (Keys .LLM .ALTUP_ACTIVE_IDX .format (arch = self .arch ),val ) 762 763def add_altup_num_inputs (self ,val :int )-> None : 764self .add_uint32 (Keys .LLM .ALTUP_NUM_INPUTS .format (arch = self .arch ),val ) 765 766def add_activation_sparsity_scale (self ,values :Sequence [float ])-> None : 767self .add_array (Keys .LLM .ACTIVATION_SPARSITY_SCALE .format (arch = self .arch ),values ) 768 769def add_head_count (self ,count :int | Sequence [int ])-> None : 770if isinstance (count ,int ): 771self .add_uint32 (Keys .Attention .HEAD_COUNT .format (arch = self .arch ),count ) 772else : 773self .add_array (Keys .Attention .HEAD_COUNT .format (arch = self .arch ),count ) 774 775def add_head_count_kv (self ,count :int | Sequence [int ])-> None : 776if isinstance (count ,int ): 777self .add_uint32 (Keys .Attention .HEAD_COUNT_KV .format (arch = self .arch ),count ) 778else : 779self .add_array (Keys .Attention .HEAD_COUNT_KV .format (arch = self .arch ),count ) 780 781def add_key_length (self ,length :int )-> None : 782self .add_uint32 (Keys .Attention .KEY_LENGTH .format (arch = self .arch ),length ) 783 784def add_value_length (self ,length :int )-> None : 785self .add_uint32 (Keys .Attention .VALUE_LENGTH .format (arch = self .arch ),length ) 786 787def add_key_length_mla (self ,length :int )-> None : 788self .add_uint32 (Keys .Attention .KEY_LENGTH_MLA .format (arch = self .arch ),length ) 789 790def add_value_length_mla (self ,length :int )-> None : 791self .add_uint32 (Keys .Attention .VALUE_LENGTH_MLA .format (arch = self .arch ),length ) 792 793def add_key_length_swa (self ,length :int )-> None : 794self .add_uint32 (Keys .Attention .KEY_LENGTH_SWA .format (arch = self .arch ),length ) 795 796def add_key_length_mla_swa (self ,length :int )-> None : 797self .add_uint32 (Keys .Attention .KEY_LENGTH_MLA_SWA .format (arch = self .arch ),length ) 798 799def add_value_length_mla_swa (self ,length :int )-> None : 800self .add_uint32 (Keys .Attention .VALUE_LENGTH_MLA_SWA .format (arch = self .arch ),length ) 801 802def add_kv_lora_rank_swa (self ,length :int )-> None : 803self .add_uint32 (Keys .Attention .KV_LORA_RANK_SWA .format (arch = self .arch ),length ) 804 805def add_value_length_swa (self ,length :int )-> None : 806self .add_uint32 (Keys .Attention .VALUE_LENGTH_SWA .format (arch = self .arch ),length ) 807 808def add_indexer_head_count (self ,count :int )-> None : 809self .add_uint32 (Keys .Attention .Indexer .HEAD_COUNT .format (arch = self .arch ),count ) 810 811def add_indexer_key_length (self ,length :int )-> None : 812self .add_uint32 (Keys .Attention .Indexer .KEY_LENGTH .format (arch = self .arch ),length ) 813 814def add_indexer_top_k (self ,top_k :int )-> None : 815self .add_uint32 (Keys .Attention .Indexer .TOP_K .format (arch = self .arch ),top_k ) 816 817def add_indexer_block_size (self ,block_size :int )-> None : 818self .add_uint32 (Keys .Attention .Indexer .BLOCK_SIZE .format (arch = self .arch ),block_size ) 819 820def add_indexer_local_blocks (self ,local_blocks :int )-> None : 821self .add_uint32 (Keys .Attention .Indexer .LOCAL_BLOCKS .format (arch = self .arch ),local_blocks ) 822 823def add_indexer_types (self ,value :Sequence [bool ])-> None : 824key = Keys .Attention .Indexer .TYPES .format (arch = self .arch ) 825self .add_array (key ,value ) 826 827def add_max_alibi_bias (self ,bias :float )-> None : 828self .add_float32 (Keys .Attention .MAX_ALIBI_BIAS .format (arch = self .arch ),bias ) 829 830def add_clamp_kqv (self ,value :float )-> None : 831self .add_float32 (Keys .Attention .CLAMP_KQV .format (arch = self .arch ),value ) 832 833def add_shared_kv_layers (self ,value :int )-> None : 834self .add_uint32 (Keys .Attention .SHARED_KV_LAYERS .format (arch = self .arch ),value ) 835 836# if input is array, true means SWA and false means full_attention for each layer 837def add_sliding_window_pattern (self ,value :int | Sequence [bool ])-> None : 838key = Keys .Attention .SLIDING_WINDOW_PATTERN .format (arch = self .arch ) 839if isinstance (value ,int ): 840self .add_uint32 (key ,value ) 841else : 842self .add_array (key ,value ) 843 844def add_recurrent_layers (self ,value :Sequence [bool ])-> None : 845self .add_array (Keys .Attention .RECURRENT_LAYERS .format (arch = self .arch ),value ) 846 847def add_rope_pattern (self ,value :Sequence [bool ])-> None : 848self .add_array (Keys .Attention .ROPE_PATTERN .format (arch = self .arch ),value ) 849 850def add_dense_features_dims (self ,dense :str ,in_f :int ,out_f :int )-> None : 851self .add_uint32 (Keys .LLM .DENSE_FEAT_IN_SIZE .format (arch = self .arch ,dense = dense ),in_f ) 852self .add_uint32 (Keys .LLM .DENSE_FEAT_OUT_SIZE .format (arch = self .arch ,dense = dense ),out_f ) 853 854def add_logit_scale (self ,value :float )-> None : 855self .add_float32 (Keys .LLM .LOGIT_SCALE .format (arch = self .arch ),value ) 856 857def add_attn_logit_softcapping (self ,value :float )-> None : 858self .add_float32 (Keys .LLM .ATTN_LOGIT_SOFTCAPPING .format (arch = self .arch ),value ) 859 860def add_router_logit_softcapping (self ,value :float )-> None : 861self .add_float32 (Keys .LLM .ROUTER_LOGIT_SOFTCAPPING .format (arch = self .arch ),value ) 862 863def add_final_logit_softcapping (self ,value :float )-> None : 864self .add_float32 (Keys .LLM .FINAL_LOGIT_SOFTCAPPING .format (arch = self .arch ),value ) 865 866def add_expert_count (self ,count :int )-> None : 867self .add_uint32 (Keys .LLM .EXPERT_COUNT .format (arch = self .arch ),count ) 868 869def add_expert_used_count (self ,count :int | Sequence [int ])-> None : 870if isinstance (count ,int ): 871self .add_uint32 (Keys .LLM .EXPERT_USED_COUNT .format (arch = self .arch ),count ) 872else : 873self .add_array (Keys .LLM .EXPERT_USED_COUNT .format (arch = self .arch ),count ) 874 875def add_expert_shared_count (self ,count :int )-> None : 876self .add_uint32 (Keys .LLM .EXPERT_SHARED_COUNT .format (arch = self .arch ),count ) 877 878def add_expert_group_count (self ,count :int )-> None : 879self .add_uint32 (Keys .LLM .EXPERT_GROUP_COUNT .format (arch = self .arch ),count ) 880 881def add_expert_group_used_count (self ,count :int )-> None : 882self .add_uint32 (Keys .LLM .EXPERT_GROUP_USED_COUNT .format (arch = self .arch ),count ) 883 884def add_expert_weights_scale (self ,value :float )-> None : 885self .add_float32 (Keys .LLM .EXPERT_WEIGHTS_SCALE .format (arch = self .arch ),value ) 886 887def add_expert_weights_norm (self ,value :bool )-> None : 888self .add_bool (Keys .LLM .EXPERT_WEIGHTS_NORM .format (arch = self .arch ),value ) 889 890def add_expert_gating_func (self ,value :ExpertGatingFuncType )-> None : 891self .add_uint32 (Keys .LLM .EXPERT_GATING_FUNC .format (arch = self .arch ),value .value ) 892 893def add_swiglu_clamp_exp (self ,values :Sequence [float ])-> None : 894self .add_array (Keys .LLM .SWIGLU_CLAMP_EXP .format (arch = self .arch ),values ) 895 896def add_swiglu_clamp_shexp (self ,values :Sequence [float ])-> None : 897self .add_array (Keys .LLM .SWIGLU_CLAMP_SHEXP .format (arch = self .arch ),values ) 898 899def add_hidden_act (self ,value :str )-> None : 900self .add_string (Keys .LLM .HIDDEN_ACT .format (arch = self .arch ),value ) 901 902def add_expert_group_scale (self ,value :float )-> None : 903self .add_float32 (Keys .LLM .EXPERT_GROUP_SCALE .format (arch = self .arch ),value ) 904 905def add_experts_per_group (self ,count :int )-> None : 906self .add_uint32 (Keys .LLM .EXPERTS_PER_GROUP .format (arch = self .arch ),count ) 907 908def add_moe_every_n_layers (self ,value :int )-> None : 909self .add_uint32 (Keys .LLM .MOE_EVERY_N_LAYERS .format (arch = self .arch ),value ) 910 911def add_moe_latent_size (self ,value :int )-> None : 912self .add_uint32 (Keys .LLM .MOE_LATENT_SIZE .format (arch = self .arch ),value ) 913 914def add_nextn_predict_layers (self ,count :int )-> None : 915self .add_uint32 (Keys .LLM .NEXTN_PREDICT_LAYERS .format (arch = self .arch ),count ) 916 917def add_swin_norm (self ,value :bool )-> None : 918self .add_bool (Keys .LLM .SWIN_NORM .format (arch = self .arch ),value ) 919 920def add_rescale_every_n_layers (self ,count :int )-> None : 921self .add_uint32 (Keys .LLM .RESCALE_EVERY_N_LAYERS .format (arch = self .arch ),count ) 922 923def add_time_mix_extra_dim (self ,dim :int )-> None : 924self .add_uint32 (Keys .LLM .TIME_MIX_EXTRA_DIM .format (arch = self .arch ),dim ) 925 926def add_time_decay_extra_dim (self ,dim :int )-> None : 927self .add_uint32 (Keys .LLM .TIME_DECAY_EXTRA_DIM .format (arch = self .arch ),dim ) 928 929def add_residual_scale (self ,value :float )-> None : 930self .add_float32 (Keys .LLM .RESIDUAL_SCALE .format (arch = self .arch ),value ) 931 932def add_embedding_scale (self ,value :float )-> None : 933self .add_float32 (Keys .LLM .EMBEDDING_SCALE .format (arch = self .arch ),value ) 934 935def add_adapter_count (self ,count :int )-> None : 936self .add_uint32 (Keys .Adapters .COUNT .format (arch = self .arch ),count ) 937 938def add_adapter_token_ids_activate (self ,ids :Sequence [int ])-> None : 939self .add_array (Keys .Adapters .TOKEN_IDS_ACTIVATE .format (arch = self .arch ),ids ) 940 941def add_adapter_token_ids_substitute (self ,ids :Sequence [int ])-> None : 942self .add_array (Keys .Adapters .TOKEN_IDS_SUBSTITUTE .format (arch = self .arch ),ids ) 943 944def add_adapter_lora_rank (self ,rank :int )-> None : 945self .add_uint32 (Keys .Adapters .LORA_RANK .format (arch = self .arch ),rank ) 946 947def add_adapter_router_gain (self ,gain :float )-> None : 948self .add_float32 (Keys .Adapters .ROUTER_GAIN .format (arch = self .arch ),gain ) 949 950def add_wkv_head_size (self ,size :int )-> None : 951self .add_uint32 (Keys .WKV .HEAD_SIZE .format (arch = self .arch ),size ) 952 953def add_token_shift_count (self ,count :int )-> None : 954self .add_uint32 (Keys .LLM .TOKEN_SHIFT_COUNT .format (arch = self .arch ),count ) 955 956def add_num_loops (self ,count :int )-> None : 957self .add_uint32 (Keys .LLM .NUM_LOOPS .format (arch = self .arch ),count ) 958 959def add_skip_loop_final_norm (self ,value :bool )-> None : 960self .add_bool (Keys .LLM .SKIP_LOOP_FINAL_NORM .format (arch = self .arch ),value ) 961 962def add_interleave_moe_layer_step (self ,value :int )-> None : 963self .add_uint32 (Keys .LLM .INTERLEAVE_MOE_LAYER_STEP .format (arch = self .arch ),value ) 964 965def add_layer_norm_eps (self ,value :float )-> None : 966self .add_float32 (Keys .Attention .LAYERNORM_EPS .format (arch = self .arch ),value ) 967 968def add_layer_norm_rms_eps (self ,value :float )-> None : 969self .add_float32 (Keys .Attention .LAYERNORM_RMS_EPS .format (arch = self .arch ),value ) 970 971def add_group_norm_eps (self ,value :float )-> None : 972self .add_float32 (Keys .Attention .GROUPNORM_EPS .format (arch = self .arch ),value ) 973 974def add_group_norm_groups (self ,value :int )-> None : 975self .add_uint32 (Keys .Attention .GROUPNORM_GROUPS .format (arch = self .arch ),value ) 976 977def add_causal_attention (self ,value :bool )-> None : 978self .add_bool (Keys .Attention .CAUSAL .format (arch = self .arch ),value ) 979 980def add_q_lora_rank (self ,length :int )-> None : 981self .add_uint32 (Keys .Attention .Q_LORA_RANK .format (arch = self .arch ),length ) 982 983def add_kv_lora_rank (self ,length :int )-> None : 984self .add_uint32 (Keys .Attention .KV_LORA_RANK .format (arch = self .arch ),length ) 985 986def add_decay_lora_rank (self ,length :int )-> None : 987self .add_uint32 (Keys .Attention .DECAY_LORA_RANK .format (arch = self .arch ),length ) 988 989def add_iclr_lora_rank (self ,length :int )-> None : 990self .add_uint32 (Keys .Attention .ICLR_LORA_RANK .format (arch = self .arch ),length ) 991 992def add_value_residual_mix_lora_rank (self ,length :int )-> None : 993self .add_uint32 (Keys .Attention .VALUE_RESIDUAL_MIX_LORA_RANK .format (arch = self .arch ),length ) 994 995def add_rope_freq_base_swa (self ,value :float )-> None : 996self .add_float32 (Keys .Rope .FREQ_BASE_SWA .format (arch = self .arch ),value ) 997 998def add_gate_lora_rank (self ,length :int )-> None : 999self .add_uint32 (Keys .Attention .GATE_LORA_RANK .format (arch = self .arch ),length ) 1000 1001def add_relative_attn_buckets_count (self ,value :int )-> None : 1002self .add_uint32 (Keys .Attention .REL_BUCKETS_COUNT .format (arch = self .arch ),value ) 1003 1004def add_sliding_window (self ,value :int )-> None : 1005self .add_uint32 (Keys .Attention .SLIDING_WINDOW .format (arch = self .arch ),value ) 1006 1007def add_block_size (self ,value :int )-> None : 1008self .add_uint32 (Keys .LLM .BLOCK_SIZE .format (arch = self .arch ),value ) 1009 1010def add_conv_kernel_size (self ,value :int )-> None : 1011self .add_uint32 (Keys .LLM .CONV_KERNEL_SIZE .format (arch = self .arch ),value ) 1012 1013def add_conv_group_size (self ,value :int )-> None : 1014self .add_uint32 (Keys .LLM .CONV_GROUP_SIZE .format (arch = self .arch ),value ) 1015 1016def add_selector_rank (self ,value :int )-> None : 1017self .add_uint32 (Keys .LLM .SELECTOR_RANK .format (arch = self .arch ),value ) 1018 1019def add_selector_top_k (self ,value :int )-> None : 1020self .add_uint32 (Keys .LLM .SELECTOR_TOP_K .format (arch = self .arch ),value ) 1021 1022def add_sample_from_anchor (self ,value :bool )-> None : 1023self .add_bool (Keys .LLM .SAMPLE_FROM_ANCHOR .format (arch = self .arch ),value ) 1024 1025def add_has_confidence_head (self ,value :bool )-> None : 1026self .add_bool (Keys .LLM .HAS_CONFIDENCE_HEAD .format (arch = self .arch ),value ) 1027 1028def add_target_layers (self ,value :Sequence [int ])-> None : 1029self .add_array (Keys .LLM .TARGET_LAYERS .format (arch = self .arch ),value ) 1030 1031def add_target_hidden_size (self ,value :int )-> None : 1032self .add_uint32 (Keys .LLM .TARGET_HIDDEN_SIZE .format (arch = self .arch ),value ) 1033 1034def add_norm_before_residual (self ,value :bool )-> None : 1035self .add_bool (Keys .LLM .NORM_BEFORE_RESIDUAL .format (arch = self .arch ),value ) 1036 1037def add_norm_before_fc (self ,value :bool )-> None : 1038self .add_bool (Keys .LLM .NORM_BEFORE_FC .format (arch = self .arch ),value ) 1039 1040def add_attention_output_group_count (self ,count :int )-> None : 1041self .add_uint32 (Keys .Attention .OUTPUT_GROUP_COUNT .format (arch = self .arch ),count ) 1042 1043def add_attention_output_lora_rank (self ,length :int )-> None : 1044self .add_uint32 (Keys .Attention .OUTPUT_LORA_RANK .format (arch = self .arch ),length ) 1045 1046def add_attention_compress_ratios (self ,values :Sequence [int ])-> None : 1047self .add_array (Keys .Attention .COMPRESS_RATIOS .format (arch = self .arch ),values ) 1048 1049def add_attention_compress_rope_freq_base (self ,value :float )-> None : 1050self .add_float32 (Keys .Attention .COMPRESS_ROPE_FREQ_BASE .format (arch = self .arch ),value ) 1051 1052def add_hyper_connection_count (self ,count :int )-> None : 1053self .add_uint32 (Keys .HyperConnection .COUNT .format (arch = self .arch ),count ) 1054 1055def add_hyper_connection_sinkhorn_iterations (self ,count :int )-> None : 1056self .add_uint32 (Keys .HyperConnection .SINKHORN_ITERATIONS .format (arch = self .arch ),count ) 1057 1058def add_hyper_connection_epsilon (self ,value :float )-> None : 1059self .add_float32 (Keys .HyperConnection .EPSILON .format (arch = self .arch ),value ) 1060 1061def add_hyper_connection_magnitude (self ,value :float )-> None : 1062self .add_float32 (Keys .HyperConnection .MAGNITUDE .format (arch = self .arch ),value ) 1063 1064def add_hyper_connection_low_rank (self ,value :int )-> None : 1065self .add_uint32 (Keys .HyperConnection .LOW_RANK .format (arch = self .arch ),value ) 1066 1067def add_ple_layers (self ,values :Sequence [int ])-> None : 1068self .add_array (Keys .PerLayerEmbedding .LAYERS .format (arch = self .arch ),values ) 1069 1070def add_ple_ngram_size (self ,value :int )-> None : 1071self .add_uint32 (Keys .PerLayerEmbedding .NGRAM_SIZE .format (arch = self .arch ),value ) 1072 1073def add_ple_heads_per_ngram (self ,value :int )-> None : 1074self .add_uint32 (Keys .PerLayerEmbedding .HEADS_PER_NGRAM .format (arch = self .arch ),value ) 1075 1076def add_ple_conv_kernel (self ,value :int )-> None : 1077self .add_uint32 (Keys .PerLayerEmbedding .CONV_KERNEL .format (arch = self .arch ),value ) 1078 1079# multipliers reach ~2.4e13; default INT32 inference would truncate them 1080def _add_u64_array (self ,key :str ,values :Sequence [int ])-> None : 1081self .add_key_value (key ,list (values ),GGUFValueType .ARRAY ,GGUFValueType .UINT64 ) 1082 1083def add_ple_layer_multipliers (self ,values :Sequence [int ])-> None : 1084self ._add_u64_array (Keys .PerLayerEmbedding .LAYER_MULTIPLIERS .format (arch = self .arch ),values ) 1085 1086def add_ple_head_offsets (self ,values :Sequence [int ])-> None : 1087self ._add_u64_array (Keys .PerLayerEmbedding .HEAD_OFFSETS .format (arch = self .arch ),values ) 1088 1089def add_ple_head_vocab_sizes (self ,values :Sequence [int ])-> None : 1090self ._add_u64_array (Keys .PerLayerEmbedding .HEAD_VOCAB_SIZES .format (arch = self .arch ),values ) 1091 1092def add_ple_eos_token_id (self ,value :int )-> None : 1093self .add_uint32 (Keys .PerLayerEmbedding .EOS_TOKEN_ID .format (arch = self .arch ),value ) 1094 1095def add_ple_image_token_id (self ,value :int )-> None : 1096self .add_uint32 (Keys .PerLayerEmbedding .IMAGE_TOKEN_ID .format (arch = self .arch ),value ) 1097 1098def add_attention_scale (self ,value :float )-> None : 1099self .add_float32 (Keys .Attention .SCALE .format (arch = self .arch ),value ) 1100 1101def add_attn_output_scale (self ,value :float )-> None : 1102self .add_float32 (Keys .Attention .OUTPUT_SCALE .format (arch = self .arch ),value ) 1103 1104def add_attn_value_scale (self ,value :float )-> None : 1105self .add_float32 (Keys .Attention .VALUE_SCALE .format (arch = self .arch ),value ) 1106 1107def add_attn_temperature_length (self ,value :int )-> None : 1108self .add_uint32 (Keys .Attention .TEMPERATURE_LENGTH .format (arch = self .arch ),value ) 1109 1110def add_attn_temperature_scale (self ,value :float )-> None : 1111self .add_float32 (Keys .Attention .TEMPERATURE_SCALE .format (arch = self .arch ),value ) 1112 1113def add_pooling_type (self ,value :PoolingType )-> None : 1114self .add_uint32 (Keys .LLM .POOLING_TYPE .format (arch = self .arch ),value .value ) 1115 1116def add_num_deepstack_layers (self ,count :int )-> None : 1117"""Add scalar deepstack layer count (qwen3vl format)""" 1118self .add_uint32 (Keys .LLM .NUM_DEEPSTACK_LAYERS .format (arch = self .arch ),count ) 1119 1120def add_deepstack_mapping (self ,layers :Sequence [int ])-> None : 1121"""Add per-layer deepstack projector indices (Granite4 Vision format)""" 1122self .add_array (Keys .LLM .DEEPSTACK_MAPPING .format (arch = self .arch ),list (layers )) 1123 1124def add_rope_dimension_count (self ,count :int )-> None : 1125self .add_uint32 (Keys .Rope .DIMENSION_COUNT .format (arch = self .arch ),count ) 1126 1127def add_rope_dimension_count_swa (self ,count :int )-> None : 1128self .add_uint32 (Keys .Rope .DIMENSION_COUNT_SWA .format (arch = self .arch ),count ) 1129 1130def add_rope_dimension_sections (self ,dims :Sequence [int ])-> None : 1131self .add_array (Keys .Rope .DIMENSION_SECTIONS .format (arch = self .arch ),dims ) 1132 1133def add_rope_freq_base (self ,value :float )-> None : 1134self .add_float32 (Keys .Rope .FREQ_BASE .format (arch = self .arch ),value ) 1135 1136def add_rope_scaling_type (self ,value :RopeScalingType )-> None : 1137self .add_string (Keys .Rope .SCALING_TYPE .format (arch = self .arch ),value .value ) 1138 1139def add_rope_scaling_factor (self ,value :float )-> None : 1140self .add_float32 (Keys .Rope .SCALING_FACTOR .format (arch = self .arch ),value ) 1141 1142def add_rope_scaling_alpha (self ,value :float )-> None : 1143self .add_float32 (Keys .Rope .SCALING_ALPHA .format (arch = self .arch ),value ) 1144 1145def add_rope_scaling_attn_factors (self ,value :float )-> None : 1146self .add_float32 (Keys .Rope .SCALING_ATTN_FACTOR .format (arch = self .arch ),value ) 1147 1148def add_rope_scaling_orig_ctx_len (self ,value :int )-> None : 1149self .add_uint32 (Keys .Rope .SCALING_ORIG_CTX_LEN .format (arch = self .arch ),value ) 1150 1151def add_rope_scaling_finetuned (self ,value :bool )-> None : 1152self .add_bool (Keys .Rope .SCALING_FINETUNED .format (arch = self .arch ),value ) 1153 1154def add_rope_scaling_yarn_log_mul (self ,value :float )-> None : 1155self .add_float32 (Keys .Rope .SCALING_YARN_LOG_MUL .format (arch = self .arch ),value ) 1156 1157def add_rope_scaling_yarn_ext_factor (self ,value :float )-> None : 1158self .add_float32 (Keys .Rope .SCALING_YARN_EXT_FACTOR .format (arch = self .arch ),value ) 1159 1160def add_rope_scaling_yarn_attn_factor (self ,value :float )-> None : 1161self .add_float32 (Keys .Rope .SCALING_YARN_ATTN_FACTOR .format (arch = self .arch ),value ) 1162 1163def add_rope_scaling_yarn_beta_fast (self ,value :float )-> None : 1164self .add_float32 (Keys .Rope .SCALING_YARN_BETA_FAST .format (arch = self .arch ),value ) 1165 1166def add_rope_scaling_yarn_beta_slow (self ,value :float )-> None : 1167self .add_float32 (Keys .Rope .SCALING_YARN_BETA_SLOW .format (arch = self .arch ),value ) 1168 1169def add_ssm_conv_kernel (self ,value :int )-> None : 1170self .add_uint32 (Keys .SSM .CONV_KERNEL .format (arch = self .arch ),value ) 1171 1172def add_ssm_inner_size (self ,value :int )-> None : 1173self .add_uint32 (Keys .SSM .INNER_SIZE .format (arch = self .arch ),value ) 1174 1175def add_ssm_state_size (self ,value :int )-> None : 1176self .add_uint32 (Keys .SSM .STATE_SIZE .format (arch = self .arch ),value ) 1177 1178def add_ssm_time_step_rank (self ,value :int )-> None : 1179self .add_uint32 (Keys .SSM .TIME_STEP_RANK .format (arch = self .arch ),value ) 1180 1181def add_ssm_group_count (self ,value :int )-> None : 1182self .add_uint32 (Keys .SSM .GROUP_COUNT .format (arch = self .arch ),value ) 1183 1184def add_ssm_dt_b_c_rms (self ,value :bool )-> None : 1185self .add_bool (Keys .SSM .DT_B_C_RMS .format (arch = self .arch ),value ) 1186 1187def add_expert_latent_length (self ,value :int )-> None : 1188self .add_uint32 (Keys .LLM .EXPERT_LATENT_LENGTH .format (arch = self .arch ),value ) 1189 1190def add_activation_situ_beta (self ,value :float )-> None : 1191self .add_float32 (Keys .Activation .SITU_BETA .format (arch = self .arch ),value ) 1192 1193def add_activation_situ_linear_beta (self ,value :float )-> None : 1194self .add_float32 (Keys .Activation .SITU_LINEAR_BETA .format (arch = self .arch ),value ) 1195 1196def add_attn_res_block_size (self ,value :int )-> None : 1197self .add_uint32 (Keys .AttnRes .BLOCK_SIZE .format (arch = self .arch ),value ) 1198 1199def add_kda_head_dim (self ,value :int )-> None : 1200self .add_uint32 (Keys .KDA .HEAD_DIM .format (arch = self .arch ),value ) 1201 1202def add_kda_safe_gate (self ,value :bool )-> None : 1203self .add_bool (Keys .KDA .SAFE_GATE .format (arch = self .arch ),value ) 1204 1205def add_kda_gate_lower_bound (self ,value :float )-> None : 1206self .add_float32 (Keys .KDA .GATE_LOWER_BOUND .format (arch = self .arch ),value ) 1207 1208def add_tokenizer_model (self ,model :str )-> None : 1209self .add_string (Keys .Tokenizer .MODEL ,model ) 1210 1211def add_tokenizer_pre (self ,pre :str )-> None : 1212self .add_string (Keys .Tokenizer .PRE ,pre ) 1213 1214def add_token_list (self ,tokens :Sequence [str ]| Sequence [bytes ]| Sequence [bytearray ])-> None : 1215self .add_array (Keys .Tokenizer .LIST ,tokens ) 1216 1217def add_token_merges (self ,merges :Sequence [str ]| Sequence [bytes ]| Sequence [bytearray ])-> None : 1218self .add_array (Keys .Tokenizer .MERGES ,merges ) 1219 1220def add_token_types (self ,types :Sequence [TokenType ]| Sequence [int ])-> None : 1221self .add_array (Keys .Tokenizer .TOKEN_TYPE ,types ) 1222 1223def add_token_type_count (self ,value :int )-> None : 1224self .add_uint32 (Keys .Tokenizer .TOKEN_TYPE_COUNT ,value ) 1225 1226def add_token_scores (self ,scores :Sequence [float ])-> None : 1227self .add_array (Keys .Tokenizer .SCORES ,scores ) 1228 1229def add_bos_token_id (self ,id :int )-> None : 1230self .add_uint32 (Keys .Tokenizer .BOS_ID ,id ) 1231 1232def add_eos_token_id (self ,id :int )-> None : 1233self .add_uint32 (Keys .Tokenizer .EOS_ID ,id ) 1234 1235def add_unk_token_id (self ,id :int )-> None : 1236self .add_uint32 (Keys .Tokenizer .UNK_ID ,id ) 1237 1238def add_sep_token_id (self ,id :int )-> None : 1239self .add_uint32 (Keys .Tokenizer .SEP_ID ,id ) 1240 1241def add_pad_token_id (self ,id :int )-> None : 1242self .add_uint32 (Keys .Tokenizer .PAD_ID ,id ) 1243 1244def add_mask_token_id (self ,id :int )-> None : 1245self .add_uint32 (Keys .Tokenizer .MASK_ID ,id ) 1246 1247def add_add_bos_token (self ,value :bool )-> None : 1248self .add_bool (Keys .Tokenizer .ADD_BOS ,value ) 1249 1250def add_add_eos_token (self ,value :bool )-> None : 1251self .add_bool (Keys .Tokenizer .ADD_EOS ,value ) 1252 1253def add_add_sep_token (self ,value :bool )-> None : 1254self .add_bool (Keys .Tokenizer .ADD_SEP ,value ) 1255 1256def add_add_space_prefix (self ,value :bool )-> None : 1257self .add_bool (Keys .Tokenizer .ADD_PREFIX ,value ) 1258 1259def add_remove_extra_whitespaces (self ,value :bool )-> None : 1260self .add_bool (Keys .Tokenizer .REMOVE_EXTRA_WS ,value ) 1261 1262def add_precompiled_charsmap (self ,charsmap :bytes )-> None : 1263self .add_array (Keys .Tokenizer .PRECOMPILED_CHARSMAP ,charsmap ) 1264 1265def add_chat_template (self ,value :str | Sequence [Mapping [str ,str ]]| None )-> None : 1266if value is None : 1267self .remove_key (Keys .Tokenizer .CHAT_TEMPLATE ) 1268return 1269 1270if not isinstance (value ,str ): 1271template_default = None 1272template_names = set () 1273 1274for choice in value : 1275name = choice .get ('name' ,'' ) 1276template = choice .get ('template' ) 1277 1278# Allowing non-alphanumerical characters in template name is probably not a good idea, so filter it 1279name = '' .join ((c if c in ascii_letters + digits else '_' for c in name )) 1280 1281if name and template is not None : 1282if name == 'default' : 1283template_default = template 1284else : 1285template_names .add (name ) 1286self .add_string (Keys .Tokenizer .CHAT_TEMPLATE_N .format (name = name ),template ) 1287 1288if template_names : 1289self .add_array (Keys .Tokenizer .CHAT_TEMPLATES ,list (template_names )) 1290 1291if template_default is None : 1292return 1293 1294value = template_default 1295 1296self .add_string (Keys .Tokenizer .CHAT_TEMPLATE ,value ) 1297 1298def add_suppress_tokens (self ,tokens :Sequence [int ])-> None : 1299self .add_array (Keys .Tokenizer .SUPPRESS_TOKENS ,tokens ) 1300 1301def add_normalizer_lowercase (self ,value :bool )-> None : 1302self .add_bool (Keys .Tokenizer .NORMALIZER_LOWERCASE ,value ) 1303 1304def add_normalizer_strip_accents (self ,value :bool )-> None : 1305self .add_bool (Keys .Tokenizer .NORMALIZER_STRIP_ACCENTS ,value ) 1306 1307def add_eot_token_id (self ,id :int )-> None : 1308self .add_uint32 (Keys .Tokenizer .EOT_ID ,id ) 1309 1310def add_eom_token_id (self ,id :int )-> None : 1311self .add_uint32 (Keys .Tokenizer .EOM_ID ,id ) 1312 1313def add_classifier_output_labels (self ,labels :Sequence [str ])-> None : 1314self .add_array (Keys .Classifier .OUTPUT_LABELS .format (arch = self .arch ),labels ) 1315 1316# for vision models 1317 1318def add_clip_has_vision_encoder (self ,value :bool )-> None : 1319self .add_bool (Keys .Clip .HAS_VISION_ENCODER ,value ) 1320 1321def add_clip_has_audio_encoder (self ,value :bool )-> None : 1322self .add_bool (Keys .Clip .HAS_AUDIO_ENCODER ,value ) 1323 1324def add_clip_has_gen_audio_encoder (self ,value :bool )-> None : 1325self .add_bool (Keys .Clip .HAS_GEN_AUDIO_ENCODER ,value ) 1326 1327def add_clip_projector_type (self ,value :str )-> None : 1328self .add_string (Keys .Clip .PROJECTOR_TYPE ,value ) 1329 1330def add_clip_vision_projector_type (self ,value :str )-> None : 1331self .add_string (Keys .ClipVision .PROJECTOR_TYPE ,value ) 1332 1333def add_vision_projection_dim (self ,value :int )-> None : 1334self .add_uint32 (Keys .ClipVision .PROJECTION_DIM ,value ) 1335 1336def add_vision_patch_size (self ,value :int )-> None : 1337self .add_uint32 (Keys .ClipVision .PATCH_SIZE ,value ) 1338 1339def add_vision_embedding_length (self ,value :int )-> None : 1340self .add_uint32 (Keys .ClipVision .EMBEDDING_LENGTH ,value ) 1341 1342def add_vision_feed_forward_length (self ,value :int )-> None : 1343self .add_uint32 (Keys .ClipVision .FEED_FORWARD_LENGTH ,value ) 1344 1345def add_vision_block_count (self ,value :int )-> None : 1346self .add_uint32 (Keys .ClipVision .BLOCK_COUNT ,value ) 1347 1348def add_vision_head_count (self ,value :int )-> None : 1349self .add_uint32 (Keys .ClipVision .Attention .HEAD_COUNT ,value ) 1350 1351def add_vision_head_count_kv (self ,value :int )-> None : 1352self .add_uint32 (Keys .ClipVision .Attention .HEAD_COUNT_KV ,value ) 1353 1354def add_vision_head_dim (self ,value :int )-> None : 1355self .add_uint32 (Keys .ClipVision .Attention .HEAD_DIM ,value ) 1356 1357def add_vision_attention_layernorm_eps (self ,value :float )-> None : 1358self .add_float32 (Keys .ClipVision .Attention .LAYERNORM_EPS ,value ) 1359 1360def add_vision_image_size (self ,value :int )-> None : 1361self .add_uint32 (Keys .ClipVision .IMAGE_SIZE ,value ) 1362 1363def add_vision_max_pixels (self ,value :int )-> None : 1364self .add_uint32 (Keys .ClipVision .IMAGE_MAX_PIXELS ,value ) 1365 1366def add_vision_min_pixels (self ,value :int )-> None : 1367self .add_uint32 (Keys .ClipVision .IMAGE_MIN_PIXELS ,value ) 1368 1369def add_vision_preproc_max_tiles (self ,value :int )-> None : 1370self .add_uint32 (Keys .ClipVision .PREPROC_MAX_TILES ,value ) 1371 1372def add_vision_preproc_min_tiles (self ,value :int )-> None : 1373self .add_uint32 (Keys .ClipVision .PREPROC_MIN_TILES ,value ) 1374 1375def add_vision_preproc_image_size (self ,value :int )-> None : 1376self .add_uint32 (Keys .ClipVision .PREPROC_IMAGE_SIZE ,value ) 1377 1378def add_vision_projector_query_side (self ,value :int )-> None : 1379self .add_uint32 (Keys .ClipVision .Projector .QUERY_SIDE ,value ) 1380 1381def add_vision_projector_window_side (self ,value :int )-> None : 1382self .add_uint32 (Keys .ClipVision .Projector .WINDOW_SIDE ,value ) 1383 1384def add_vision_spatial_offsets (self ,layers :Sequence [int ])-> None : 1385self .add_array (Keys .ClipVision .Projector .SPATIAL_OFFSETS ,layers ) 1386 1387def add_vision_image_mean (self ,values :Sequence [float ])-> None : 1388self .add_array (Keys .ClipVision .IMAGE_MEAN ,values ) 1389 1390def add_vision_image_std (self ,values :Sequence [float ])-> None : 1391self .add_array (Keys .ClipVision .IMAGE_STD ,values ) 1392 1393def add_vision_spatial_merge_size (self ,value :int )-> None : 1394self .add_uint32 (Keys .ClipVision .SPATIAL_MERGE_SIZE ,value ) 1395 1396def add_vision_expert_count_per_layer (self ,value :Sequence [int ])-> None : 1397self .add_array (Keys .ClipVision .EXPERT_COUNT_PER_LAYER ,value ) 1398 1399def add_vision_expert_used_count (self ,value :int )-> None : 1400self .add_uint32 (Keys .ClipVision .EXPERT_USED_COUNT ,value ) 1401 1402def add_vision_use_gelu (self ,value :bool )-> None : 1403self .add_bool (Keys .ClipVision .USE_GELU ,value ) 1404 1405def add_vision_use_silu (self ,value :bool )-> None : 1406self .add_bool (Keys .ClipVision .USE_SILU ,value ) 1407 1408def add_vision_projector_scale_factor (self ,value :int )-> None : 1409self .add_uint32 (Keys .ClipVision .Projector .SCALE_FACTOR ,value ) 1410 1411def add_vision_n_wa_pattern (self ,value :int )-> None : 1412"""Add window attention pattern interval for vision models. 1413 1414This defines the pattern interval for window attention vs full attention layers. 1415For example, if n_wa_pattern=4, then layers 3, 7, 11, ... use full attention, 1416while other layers use window attention. 1417 1418Used by models like Qwen2.5-VL where full attention layers follow a regular pattern. 1419""" 1420self .add_uint32 (Keys .ClipVision .N_WA_PATTERN ,value ) 1421 1422def add_vision_wa_layer_indexes (self ,layers :Sequence [int ])-> None : 1423"""Add explicit layer indexes that use full attention in vision models. 1424 1425This specifies the exact layer indices (0-based) that should use full attention 1426instead of window attention. All other layers will use window attention. 1427 1428Args: 1429layers: List of layer indices that use full attention (e.g., [3, 7, 11, 15]) 1430 1431Used by models like YoutuVL where full attention layers are explicitly specified 1432rather than following a regular pattern. 1433 1434Difference from add_vision_n_wa_pattern: 1435- n_wa_pattern: Defines a regular interval pattern (every Nth layer uses full attention) 1436- wa_layer_indexes: Explicitly lists which layers use full attention (irregular pattern) 1437""" 1438self .add_array (Keys .ClipVision .WA_LAYER_INDEXES ,layers ) 1439 1440def add_vision_is_deepstack_layers (self ,layers :Sequence [bool ])-> None : 1441self .add_array (Keys .ClipVision .IS_DEEPSTACK_LAYERS ,layers ) 1442 1443def add_vision_wa_pattern_mode (self ,modes :Sequence [int ])-> None : 1444self .add_array (Keys .ClipVision .WA_PATTERN_MODE ,modes ) 1445 1446def add_vision_window_size (self ,value :int )-> None : 1447self .add_uint32 (Keys .ClipVision .WINDOW_SIZE ,value ) 1448 1449def add_vision_feature_layers (self ,layers :Sequence [int ])-> None : 1450self .add_array (Keys .ClipVision .FEATURE_LAYERS ,layers ) 1451 1452def add_vision_image_grid_pinpoints (self ,layers :Sequence [Sequence [int ]])-> None : 1453self .add_array (Keys .ClipVision .IMAGE_GRID_PINPOINTS ,layers ) 1454 1455def add_vision_sam_layers_count (self ,value :int )-> None : 1456self .add_uint32 (Keys .ClipVision .SAM .BLOCK_COUNT ,value ) 1457 1458def add_vision_sam_embedding_length (self ,value :int )-> None : 1459self .add_uint32 (Keys .ClipVision .SAM .EMBEDDING_LENGTH ,value ) 1460 1461def add_vision_sam_head_count (self ,value :int )-> None : 1462self .add_uint32 (Keys .ClipVision .SAM .HEAD_COUNT ,value ) 1463 1464# audio models 1465 1466def add_clip_audio_projector_type (self ,value :str )-> None : 1467self .add_string (Keys .ClipAudio .PROJECTOR_TYPE ,value ) 1468 1469def add_audio_projection_dim (self ,value :int )-> None : 1470self .add_uint32 (Keys .ClipAudio .PROJECTION_DIM ,value ) 1471 1472def add_audio_embedding_length (self ,value :int )-> None : 1473self .add_uint32 (Keys .ClipAudio .EMBEDDING_LENGTH ,value ) 1474 1475def add_audio_feed_forward_length (self ,value :int )-> None : 1476self .add_uint32 (Keys .ClipAudio .FEED_FORWARD_LENGTH ,value ) 1477 1478def add_audio_block_count (self ,value :int )-> None : 1479self .add_uint32 (Keys .ClipAudio .BLOCK_COUNT ,value ) 1480 1481def add_audio_head_count (self ,value :int )-> None : 1482self .add_uint32 (Keys .ClipAudio .Attention .HEAD_COUNT ,value ) 1483 1484def add_audio_attention_layernorm_eps (self ,value :float )-> None : 1485self .add_float32 (Keys .ClipAudio .Attention .LAYERNORM_EPS ,value ) 1486 1487def add_audio_num_mel_bins (self ,value :int )-> None : 1488self .add_uint32 (Keys .ClipAudio .NUM_MEL_BINS ,value ) 1489 1490def add_audio_rvq_num_quantizers (self ,value :int )-> None : 1491self .add_uint32 (Keys .ClipAudio .RVQ_NUM_QUANTIZERS ,value ) 1492 1493def add_audio_rvq_codebook_size (self ,values :Sequence [int ])-> None : 1494self .add_array (Keys .ClipAudio .RVQ_CODEBOOK_SIZE ,values ) 1495 1496def add_audio_wa_pattern_mode (self ,modes :Sequence [int ])-> None : 1497self .add_array (Keys .ClipAudio .WA_PATTERN_MODE ,modes ) 1498 1499def add_audio_window_size (self ,value :int )-> None : 1500self .add_uint32 (Keys .ClipAudio .WINDOW_SIZE ,value ) 1501 1502def add_audio_local_block_count (self ,value :int )-> None : 1503self .add_uint32 (Keys .ClipAudio .LOCAL_BLOCK_COUNT ,value ) 1504 1505def add_audio_local_group_size (self ,value :int )-> None : 1506self .add_uint32 (Keys .ClipAudio .LOCAL_GROUP_SIZE ,value ) 1507 1508def add_audio_stack_factor (self ,value :int )-> None : 1509self .add_uint32 (Keys .ClipAudio .Projector .STACK_FACTOR ,value ) 1510 1511def add_audio_subsampling_factor (self ,value :int )-> None : 1512self .add_uint32 (Keys .ClipAudio .SUBSAMPLING_FACTOR ,value ) 1513 1514def add_audio_chunk_size (self ,value :int )-> None : 1515self .add_uint32 (Keys .ClipAudio .CHUNK_SIZE ,value ) 1516 1517def add_audio_conv_kernel_size (self ,value :int )-> None : 1518self .add_uint32 (Keys .ClipAudio .CONV_KERNEL_SIZE ,value ) 1519 1520def add_audio_max_pos_emb (self ,value :int )-> None : 1521self .add_uint32 (Keys .ClipAudio .MAX_POS_EMB ,value ) 1522 1523def add_audio_feature_layers (self ,layers :Sequence [int ])-> None : 1524self .add_array (Keys .ClipAudio .FEATURE_LAYERS ,layers ) 1525 1526def add_audio_projector_window_size (self ,value :int )-> None : 1527self .add_uint32 (Keys .ClipAudio .Projector .WINDOW_SIZE ,value ) 1528 1529def add_audio_projector_downsample_rate (self ,value :int )-> None : 1530self .add_uint32 (Keys .ClipAudio .Projector .DOWNSAMPLE_RATE ,value ) 1531 1532def add_audio_projector_head_count (self ,value :int )-> None : 1533self .add_uint32 (Keys .ClipAudio .Projector .HEAD_COUNT ,value ) 1534 1535# audio generation (mmproj) 1536 1537def add_clip_gen_audio_projector_type (self ,value :str )-> None : 1538self .add_string (Keys .ClipGenAudio .PROJECTOR_TYPE ,value ) 1539 1540def add_gen_audio_projection_dim (self ,value :int )-> None : 1541self .add_uint32 (Keys .ClipGenAudio .PROJECTION_DIM ,value ) 1542 1543def add_gen_audio_embedding_length (self ,value :int )-> None : 1544self .add_uint32 (Keys .ClipGenAudio .EMBEDDING_LENGTH ,value ) 1545 1546def add_gen_audio_feed_forward_length (self ,value :int )-> None : 1547self .add_uint32 (Keys .ClipGenAudio .FEED_FORWARD_LENGTH ,value ) 1548 1549def add_gen_audio_block_count (self ,value :int )-> None : 1550self .add_uint32 (Keys .ClipGenAudio .BLOCK_COUNT ,value ) 1551 1552def add_gen_audio_head_count (self ,value :int )-> None : 1553self .add_uint32 (Keys .ClipGenAudio .Attention .HEAD_COUNT ,value ) 1554 1555def add_gen_audio_head_count_kv (self ,value :int )-> None : 1556self .add_uint32 (Keys .ClipGenAudio .Attention .HEAD_COUNT_KV ,value ) 1557 1558def add_gen_audio_attention_layernorm_eps (self ,value :float )-> None : 1559self .add_float32 (Keys .ClipGenAudio .Attention .LAYERNORM_EPS ,value ) 1560 1561def add_gen_audio_model_variant (self ,value :str )-> None : 1562self .add_string (Keys .ClipGenAudio .MODEL_VARIANT ,value ) 1563 1564def add_xielu_alpha_p (self ,values :Sequence [float ]): 1565self .add_array (Keys .xIELU .ALPHA_P ,values ) 1566 1567def add_xielu_alpha_n (self ,values :Sequence [float ]): 1568self .add_array (Keys .xIELU .ALPHA_N ,values ) 1569 1570def add_xielu_beta (self ,values :Sequence [float ]): 1571self .add_array (Keys .xIELU .BETA ,values ) 1572 1573def add_xielu_eps (self ,values :Sequence [float ]): 1574self .add_array (Keys .xIELU .EPS ,values ) 1575 1576# diffusion models 1577 1578def add_diffusion_shift_logits (self ,value :bool )-> None : 1579self .add_bool (Keys .Diffusion .SHIFT_LOGITS ,value ) 1580 1581def _pack (self ,fmt :str ,value :Any ,skip_pack_prefix :bool = False )-> bytes : 1582pack_prefix = '' 1583if not skip_pack_prefix : 1584pack_prefix = '<' if self .endianess == GGUFEndian .LITTLE else '>' 1585return struct .pack (f' { pack_prefix } { fmt } ' ,value ) 1586 1587def _pack_val (self ,val :Any ,vtype :GGUFValueType ,add_vtype :bool ,sub_type :GGUFValueType | None = None )-> bytes : 1588kv_data = bytearray () 1589 1590if add_vtype : 1591kv_data += self ._pack ("I" ,vtype ) 1592 1593pack_fmt = self ._simple_value_packing .get (vtype ) 1594if pack_fmt is not None : 1595kv_data += self ._pack (pack_fmt ,val ,skip_pack_prefix = vtype == GGUFValueType .BOOL ) 1596elif vtype == GGUFValueType .STRING : 1597encoded_val = val .encode ("utf-8" )if isinstance (val ,str )else val 1598kv_data += self ._pack ("Q" ,len (encoded_val )) 1599kv_data += encoded_val 1600elif vtype == GGUFValueType .ARRAY : 1601 1602if not isinstance (val ,Sequence ): 1603raise ValueError ("Invalid GGUF metadata array, expecting sequence" ) 1604 1605if len (val )== 0 : 1606raise ValueError ("Invalid GGUF metadata array. Empty array" ) 1607 1608if sub_type is not None : 1609ltype = sub_type 1610elif isinstance (val ,bytes ): 1611ltype = GGUFValueType .UINT8 1612else : 1613ltype = GGUFValueType .get_type (val [0 ]) 1614if not all (GGUFValueType .get_type (i )is ltype for i in val [1 :]): 1615raise ValueError ("All items in a GGUF array should be of the same type" ) 1616kv_data += self ._pack ("I" ,ltype ) 1617kv_data += self ._pack ("Q" ,len (val )) 1618for item in val : 1619kv_data += self ._pack_val (item ,ltype ,add_vtype = False ) 1620else : 1621raise ValueError ("Invalid GGUF metadata value type or value" ) 1622 1623return bytes (kv_data ) 1624 1625@staticmethod 1626def format_n_bytes_to_str (num :int )-> str : 1627if num == 0 : 1628return "negligible - metadata only" 1629fnum = float (num ) 1630for unit in ("" ,"K" ,"M" ,"G" ): 1631if abs (fnum )< 1000.0 : 1632return f" { fnum :3.1f } { unit } " 1633fnum /= 1000.0 1634return f" { fnum :.1f } T - over 1TB, split recommended"