char-fork/llama.cpp
git clone https://git.t4t.associates/char-fork/llama.cpp
ffaafde16
char/aliceai-t5-moe
1#!/usr/bin/env python3 2""" 3# Generated by Claude AI 4 5Script to completely regenerate the GGML remoting codebase from YAML configuration. 6 7This script reads api_functions.yaml and regenerates all the header files and 8implementation templates for the GGML remoting layer. 9 10Usage: 11python regenerate_remoting.py 12 13The script will: 141. Read ggmlremoting_functions.yaml configuration 152. Generate updated header files 163. Generate implementation templates in dedicated files 174. Show a summary of what was generated 18""" 19 20import yaml 21from typing import Dict ,List ,Any 22from pathlib import Path 23import os 24import subprocess 25import shutil 26import logging 27 28NL = '\n' # can't have f"{'\n'}" in f-strings 29 30 31class RemotingCodebaseGenerator : 32def __init__ (self ,yaml_path :str = "ggmlremoting_functions.yaml" ): 33"""Initialize the generator with the YAML configuration.""" 34self .yaml_path = yaml_path 35 36if not Path (yaml_path ).exists (): 37raise FileNotFoundError (f"Configuration file { yaml_path } not found" ) 38 39with open (yaml_path ,'r' )as f : 40self .config = yaml .safe_load (f ) 41 42self .functions = self .config ['functions' ] 43self .naming_patterns = self .config ['naming_patterns' ] 44self .config_data = self .config ['config' ] 45 46# Check if clang-format is available 47self .clang_format_available = self ._check_clang_format_available () 48 49def _check_clang_format_available (self )-> bool : 50"""Check if clang-format is available in the system PATH.""" 51return shutil .which ("clang-format" )is not None 52 53def _format_file_with_clang_format (self ,file_path :Path )-> bool : 54"""Format a file with clang-format -i. Returns True if successful, False otherwise.""" 55if not self .clang_format_available : 56return False 57 58try : 59subprocess .run ( 60 ["clang-format" ,"-i" ,str (file_path )], 61check = True , 62capture_output = True , 63text = True 64 ) 65return True 66except subprocess .CalledProcessError : 67logging .exception (f" ⚠️ clang-format failed for { file_path } " ) 68return False 69except Exception as e : 70logging .exception (f" ⚠️ Unexpected error formatting { file_path } : { e } " ) 71return False 72 73def generate_enum_name (self ,group_name :str ,function_name :str )-> str : 74"""Generate the APIR_COMMAND_TYPE enum name for a function.""" 75prefix = self .naming_patterns ['enum_prefix' ] 76return f" { prefix } { group_name . upper () } _ { function_name . upper () } " 77 78def generate_backend_function_name (self ,group_name :str ,function_name :str )-> str : 79"""Generate the backend function name.""" 80function_key = f" { group_name } _ { function_name } " 81overrides = self .naming_patterns .get ('backend_function_overrides' , {}) 82 83if function_key in overrides : 84return overrides [function_key ] 85 86prefix = self .naming_patterns ['backend_function_prefix' ] 87return f" { prefix } { group_name } _ { function_name } " 88 89def generate_frontend_function_name (self ,group_name :str ,function_name :str )-> str : 90"""Generate the frontend function name.""" 91prefix = self .naming_patterns ['frontend_function_prefix' ] 92return f" { prefix } { group_name } _ { function_name } " 93 94def get_enabled_functions (self )-> List [Dict [str ,Any ]]: 95"""Get all enabled functions with their metadata.""" 96functions = [] 97enum_value = 0 98 99for group_name ,group_data in self .functions .items (): 100group_description = group_data ['group_description' ] 101 102for function_name ,func_metadata in group_data ['functions' ].items (): 103# Handle case where func_metadata is None or empty (functions with only comments) 104if func_metadata is None : 105func_metadata = {} 106 107# Functions are enabled by default unless explicitly disabled 108if func_metadata .get ('enabled' ,True ): 109functions .append ({ 110'group_name' :group_name , 111'function_name' :function_name , 112'enum_name' :self .generate_enum_name (group_name ,function_name ), 113'enum_value' :enum_value , 114'backend_function' :self .generate_backend_function_name (group_name ,function_name ), 115'frontend_function' :self .generate_frontend_function_name (group_name ,function_name ), 116'frontend_return' :func_metadata .get ('frontend_return' ,'void' ), 117'frontend_extra_params' :func_metadata .get ('frontend_extra_params' , []), 118'group_description' :group_description , 119'deprecated' :func_metadata .get ('deprecated' ,False ), 120 }) 121enum_value += 1 122 123return functions 124 125def generate_apir_backend_header (self )-> str : 126"""Generate the complete apir_backend.h file.""" 127functions = self .get_enabled_functions () 128 129# Generate the enum section 130enum_lines = ["typedef enum ApirBackendCommandType {" ] 131current_group = None 132 133for func in functions : 134# Add comment for new group 135if func ['group_name' ]!= current_group : 136enum_lines .append ("" ) 137enum_lines .append (f" /* { func [ 'group_description' ] } */" ) 138current_group = func ['group_name' ] 139 140enum_lines .append (f" { func [ 'enum_name' ] } = { func [ 'enum_value' ] } ," ) 141 142# Add the count 143total_count = len (functions ) 144enum_lines .append ("\n // last command_type index + 1" ) 145enum_lines .append (f" APIR_BACKEND_DISPATCH_TABLE_COUNT = { total_count } ," ) 146enum_lines .append ("} ApirBackendCommandType;" ) 147 148# Generate function name mapping 149func_lines = [] 150func_lines .append ("static inline const char * apir_dispatch_command_name(ApirBackendCommandType type) {" ) 151func_lines .append (" switch (type) {" ) 152 153current_group = None 154for func in functions : 155# Add comment for new group 156if func ['group_name' ]!= current_group : 157func_lines .append (f" /* { func [ 'group_description' ] } */" ) 158current_group = func ['group_name' ] 159 160# Generate clean function name without backend_ prefix 161clean_name = f" { func [ 'group_name' ] } _ { func [ 'function_name' ] } " 162func_lines .append (f" case { func [ 'enum_name' ] } :" ) 163func_lines .append (f" return \" { clean_name } \";" ) 164 165func_lines .append ("" ) 166func_lines .append (" default:" ) 167func_lines .append (" return \"unknown\";" ) 168func_lines .append (" }" ) 169func_lines .append ("}" ) 170 171# Full header template 172header_content = NL .join (enum_lines )+ "\n\n" + NL .join (func_lines )+ "\n" 173 174return header_content 175 176def generate_backend_dispatched_header (self )-> str : 177"""Generate the complete backend-dispatched.h file.""" 178functions = self .get_enabled_functions () 179 180# Function declarations 181decl_lines = [] 182current_group = None 183 184for func in functions : 185if func ['group_name' ]!= current_group : 186decl_lines .append (f"\n/* { func [ 'group_description' ] } */" ) 187current_group = func ['group_name' ] 188 189signature = "uint32_t" 190params = "apir_encoder *enc, apir_decoder *dec, virgl_apir_context *ctx" 191if func ['deprecated' ]: 192decl_lines .append (f"/* { func [ 'enum_name' ] } is deprecated. Keeping the handler for backward compatibility. */" ) 193 194decl_lines .append (f" { signature } { func [ 'backend_function' ] } ( { params } );" ) 195 196# Dispatch table 197table_lines = [] 198current_group = None 199 200for func in functions : 201if func ['group_name' ]!= current_group : 202table_lines .append (f"\n /* { func [ 'group_description' ] } */" ) 203table_lines .append ("" ) 204current_group = func ['group_name' ] 205 206deprecated = " /* DEPRECATED */" if func ['deprecated' ]else "" 207table_lines .append (f" /* { func [ 'enum_name' ] } = */ { func [ 'backend_function' ] } { deprecated } ," ) 208 209header_content = f'''\ 210#pragma once 211 212{ NL . join ( decl_lines ) } 213 214extern "C" {{ 215static const backend_dispatch_t apir_backend_dispatch_table[APIR_BACKEND_DISPATCH_TABLE_COUNT] = {{ 216{ NL . join ( table_lines ) } 217}}; 218}} 219''' 220return header_content 221 222def generate_virtgpu_forward_header (self )-> str : 223"""Generate the complete virtgpu-forward.gen.h file.""" 224functions = self .get_enabled_functions () 225 226decl_lines = [] 227current_group = None 228 229for func in functions : 230if func ['group_name' ]!= current_group : 231decl_lines .append ("" ) 232decl_lines .append (f"/* { func [ 'group_description' ] } */" ) 233current_group = func ['group_name' ] 234 235if func ['deprecated' ]: 236decl_lines .append (f"/* { func [ 'frontend_function' ] } is deprecated. */" ) 237continue 238 239# Build parameter list 240params = [self .naming_patterns ['frontend_base_param' ]] 241params .extend (func ['frontend_extra_params' ]) 242param_str = ', ' .join (params ) 243 244decl_lines .append (f" { func [ 'frontend_return' ] } { func [ 'frontend_function' ] } ( { param_str } );" ) 245 246header_content = f'''\ 247#pragma once 248{ NL . join ( decl_lines ) } 249''' 250return header_content 251 252def regenerate_codebase (self )-> None : 253"""Regenerate the entire remoting codebase.""" 254logging .info ("🔄 Regenerating GGML Remoting Codebase..." ) 255logging .info ("=" * 50 ) 256 257# Detect if we're running from frontend directory 258current_dir = os .getcwd () 259is_frontend_dir = current_dir .endswith ('ggml-virtgpu' ) 260 261if is_frontend_dir : 262# Running from ggml/src/ggml-virtgpu-apir 263logging .info ("📍 Detected frontend directory execution" ) 264frontend_base = Path ("." ) 265else : 266# Running from project root (fallback to original behavior) 267logging .info ("📍 Detected project root execution" ) 268base_path = self .config_data .get ('base_path' ,'ggml/src' ) 269frontend_base = Path (base_path )/ "ggml-virtgpu" 270 271# Compute final file paths 272backend_base = frontend_base / "backend" 273apir_backend_path = backend_base / "shared" / "apir_backend.gen.h" 274backend_dispatched_path = backend_base / "backend-dispatched.gen.h" 275virtgpu_forward_path = frontend_base / "virtgpu-forward.gen.h" 276 277# Create output directories for each file 278apir_backend_path .parent .mkdir (parents = True ,exist_ok = True ) 279backend_dispatched_path .parent .mkdir (parents = True ,exist_ok = True ) 280virtgpu_forward_path .parent .mkdir (parents = True ,exist_ok = True ) 281 282# Generate header files 283logging .info ("📁 Generating header files..." ) 284 285apir_backend_content = self .generate_apir_backend_header () 286apir_backend_path .write_text (apir_backend_content ) 287logging .info (f" ✅ { apir_backend_path . resolve () } " ) 288 289backend_dispatched_content = self .generate_backend_dispatched_header () 290backend_dispatched_path .write_text (backend_dispatched_content ) 291logging .info (f" ✅ { backend_dispatched_path . resolve () } " ) 292 293virtgpu_forward_content = self .generate_virtgpu_forward_header () 294virtgpu_forward_path .write_text (virtgpu_forward_content ) 295logging .info (f" ✅ { virtgpu_forward_path . resolve () } " ) 296 297# Format generated files with clang-format 298generated_files = [apir_backend_path ,backend_dispatched_path ,virtgpu_forward_path ] 299 300if not self .clang_format_available : 301logging .warning ("\n⚠️clang-format not found in PATH. Generated files will not be formatted.\n" 302" Install clang-format to enable automatic code formatting." ) 303else : 304logging .info ("\n🎨 Formatting files with clang-format..." ) 305for file_path in generated_files : 306if self ._format_file_with_clang_format (file_path ): 307logging .info (f" ✅ Formatted { file_path . name } " ) 308else : 309logging .warning (f" ❌ Failed to format { file_path . name } " ) 310 311# Generate summary 312functions = self .get_enabled_functions () 313total_functions = len (functions ) 314 315logging .info ("\n📊 Generation Summary:" ) 316logging .info ("=" * 50 ) 317logging .info (f" Total functions: { total_functions } " ) 318logging .info (f" Function groups: { len ( self . functions ) } " ) 319logging .info (" Header files: 3" ) 320logging .info (f" Working directory: { current_dir } " ) 321 322 323def main (): 324try : 325generator = RemotingCodebaseGenerator () 326generator .regenerate_codebase () 327except Exception as e : 328logging .exception (f"❌ Error: { e } " ) 329exit (1 ) 330 331 332if __name__ == "__main__" : 333main ()