Upload 4 files
Browse filesFiles changed (4)
- utils/__init__.pyAdded+1
- utils/banner.pyAdded+130
- utils/hardware.pyAdded+202
- utils/quantization.pyAdded+129
1"""Shulker Code — Utils Package"""123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130"""===================================== Shulker Code — CLI Banner Developed by @kopeedev / CyeroX====================================="""
from rich.console import Consolefrom rich.text import Textfrom rich.panel import Panelfrom rich.table import Tablefrom rich import box
console = Console()
# ASCII Art Banner for Shulker CodeSHULKER_BANNER = r""" _____ _ _ _ ____ _/ ____| | | | | / ___|___ __| | ___\\___ \| |__ _ _| | | _____ _ _| | / _ \\ / _` |/ _ \\ ___) | '_ \\| | | | | |/ / _ \\ '__| |__| (_) | (_| | __/|____/|_| |_|\\__,_|_|_|_< __/ | \\____\\___/ \\__,_|\\___| \\___|_|"""
def print_banner(version: str = "1.0.0"): """Print the Shulker Code CLI banner.""" console.print()
# Gradient-like colored banner banner_lines = SHULKER_BANNER.strip().split("\n") colors = ["bright_cyan", "cyan", "bright_blue", "blue", "bright_magenta", "magenta"]
for i, line in enumerate(banner_lines): color = colors[i % len(colors)] console.print(f" [bold {color}]{line}[/]")
console.print() console.print(f" [dim]v{version} · Code Intelligence Engine · by [bold cyan]@kopeedev[/bold cyan] / CyeroX Dev[/dim]") console.print()
def print_hardware_info(profile): """Print a hardware detection summary.""" table = Table( title="🖥️ Hardware Profile", box=box.ROUNDED, border_style="cyan", show_header=True, ) table.add_column("Property", style="dim", width=18) table.add_column("Value", style="bold")
table.add_row("Device", f"{profile.device_type.upper()} × {profile.device_count}") table.add_row("VRAM", f"{profile.total_vram_gb:.1f} GB") table.add_row("RAM", f"{profile.total_ram_gb:.1f} GB") table.add_row("FP16", "✅ Yes" if profile.supports_fp16 else "❌ No") table.add_row("BF16", "✅ Yes" if profile.supports_bf16 else "❌ No") table.add_row("Flash Attn", "✅ Yes" if profile.supports_flash_attn else "❌ No") table.add_row("Recommended", f"[bold green]shulker-{profile.recommended_variant}[/]") table.add_row("Quantization", f"[yellow]{profile.recommended_quant or 'None'}[/]")
console.print(table) console.print()
def print_generation_header(prompt: str, model_name: str = "shulker-nano"): """Print header before generation output.""" console.print(Panel( f"[dim]{prompt[:100]}{'...' if len(prompt) > 100 else ''}[/dim]", title=f"[bold cyan]🧱 {model_name}[/bold cyan]", border_style="cyan", padding=(0, 1), )) console.print()
def print_model_info(config, num_params: int): """Print model architecture summary.""" table = Table( title=f"🧠 {config.name} Architecture", box=box.ROUNDED, border_style="magenta", ) table.add_column("Parameter", style="dim") table.add_column("Value", style="bold")
table.add_row("Total Parameters", f"{num_params:,}") table.add_row("Layers", str(config.num_layers)) table.add_row("Attention Heads", str(config.num_heads)) table.add_row("KV Heads", str(config.num_kv_heads)) table.add_row("Hidden Size", str(config.hidden_size)) table.add_row("FFN Size", str(config.intermediate_size)) table.add_row("Max Seq Length", str(config.max_seq_len)) table.add_row("Vocab Size", f"{config.vocab_size:,}") table.add_row("RoPE Theta", str(config.rope_theta))
console.print(table) console.print()
def print_training_start(config: dict, total_steps: int): """Print training start summary.""" console.print(Panel( f"[bold green]🚀 Training started![/]\n" f" Batch size: [cyan]{config.get('batch_size', '?')}[/]\n" f" Max steps: [cyan]{total_steps:,}[/]\n" f" Learning rate:[cyan]{config.get('learning_rate', '?')}[/]\n" f" Mixed prec: [cyan]{'BF16' if config.get('bf16') else 'FP16' if config.get('fp16') else 'FP32'}[/]", title="[bold]Training Configuration[/]", border_style="green", )) console.print()
def print_success(message: str): console.print(f"[bold green]✅ {message}[/]")
def print_error(message: str): console.print(f"[bold red]❌ {message}[/]")
def print_warning(message: str): console.print(f"[bold yellow]⚠️ {message}[/]")
def print_info(message: str): console.print(f"[cyan]ℹ️ {message}[/]")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202"""===================================== Shulker Code — Hardware Utilities Auto-detect and optimize for device Developed by @kopeedev / CyeroX====================================="""
import osimport sysfrom typing import Optional, Tuple, Dict, Anyfrom dataclasses import dataclass
import torchimport torch.nn as nn
@dataclassclass HardwareProfile: """Detected hardware profile for optimizing model loading.""" device_type: str # "cpu", "cuda", "mps" device_count: int # Number of GPUs total_vram_gb: float # Total VRAM in GB total_ram_gb: float # Total system RAM in GB supports_fp16: bool # Hardware FP16 support supports_bf16: bool # Hardware BF16 support supports_flash_attn: bool # Flash Attention support recommended_variant: str # "nano", "small", "medium", "large", "xlarge" recommended_quant: Optional[str] # "int8", "int4", or None
def summary(self) -> str: lines = [ f" Device: {self.device_type.upper()} × {self.device_count}", f" VRAM: {self.total_vram_gb:.1f} GB", f" RAM: {self.total_ram_gb:.1f} GB", f" FP16: {'✅' if self.supports_fp16 else '❌'}", f" BF16: {'✅' if self.supports_bf16 else '❌'}", f" Flash Attn: {'✅' if self.supports_flash_attn else '❌'}", f" Recommended: shulker-{self.recommended_variant}", f" Quantization: {self.recommended_quant or 'None (full precision)'}", ] return "\n".join(lines)
def detect_hardware() -> HardwareProfile: """ Auto-detect hardware and return an optimized profile. Detects: CPU, CUDA GPU(s), Apple Silicon MPS. """ import psutil
total_ram_gb = psutil.virtual_memory().total / (1024 ** 3) total_vram_gb = 0.0 device_type = "cpu" device_count = 0 supports_fp16 = False supports_bf16 = False supports_flash_attn = False
# Check CUDA if torch.cuda.is_available(): device_type = "cuda" device_count = torch.cuda.device_count() for i in range(device_count): props = torch.cuda.get_device_properties(i) total_vram_gb += props.total_memory / (1024 ** 3) # BF16 requires Ampere (sm_80) or newer if props.major >= 8: supports_bf16 = True # FP16 requires Volta (sm_70) or newer if props.major >= 7: supports_fp16 = True
# Flash Attention available in PyTorch 2.0+ supports_flash_attn = ( int(torch.__version__.split(".")[0]) >= 2 )
# Check Apple Silicon MPS elif hasattr(torch.backends, "mps") and torch.backends.mps.is_available(): device_type = "mps" device_count = 1 # MPS doesn't expose VRAM separately; approximate from RAM total_vram_gb = total_ram_gb * 0.7 # Unified memory supports_fp16 = True supports_bf16 = False
# Determine recommended variant based on VRAM/RAM if device_type == "cuda": if total_vram_gb >= 80: recommended_variant = "xlarge" recommended_quant = None elif total_vram_gb >= 40: recommended_variant = "large" recommended_quant = None elif total_vram_gb >= 20: recommended_variant = "medium" recommended_quant = None elif total_vram_gb >= 8: recommended_variant = "small" recommended_quant = None elif total_vram_gb >= 4: recommended_variant = "small" recommended_quant = "int8" else: recommended_variant = "nano" recommended_quant = "int8" elif device_type == "mps": if total_ram_gb >= 32: recommended_variant = "small" recommended_quant = None else: recommended_variant = "nano" recommended_quant = None else: # CPU only if total_ram_gb >= 32: recommended_variant = "nano" recommended_quant = "int8" else: recommended_variant = "nano" recommended_quant = "int8"
return HardwareProfile( device_type=device_type, device_count=device_count, total_vram_gb=total_vram_gb, total_ram_gb=total_ram_gb, supports_fp16=supports_fp16, supports_bf16=supports_bf16, supports_flash_attn=supports_flash_attn, recommended_variant=recommended_variant, recommended_quant=recommended_quant, )
def get_device(device: str = "auto") -> torch.device: """ Resolve device string to torch.device. "auto" → picks best available device. """ if device == "auto": if torch.cuda.is_available(): return torch.device("cuda") elif hasattr(torch.backends, "mps") and torch.backends.mps.is_available(): return torch.device("mps") else: return torch.device("cpu") return torch.device(device)
def setup_distributed() -> Tuple[int, int, bool]: """ Initialize distributed training (DDP). Returns: (rank, world_size, is_main_process) """ if "RANK" not in os.environ: return 0, 1, True
import torch.distributed as dist
dist.init_process_group(backend="nccl") rank = dist.get_rank() world_size = dist.get_world_size() torch.cuda.set_device(rank)
return rank, world_size, rank == 0
def get_dtype(fp16: bool = False, bf16: bool = False) -> torch.dtype: """Get the appropriate tensor dtype.""" if bf16: return torch.bfloat16 elif fp16: return torch.float16 return torch.float32
def model_to_device(model: nn.Module, device: str = "auto", dtype: Optional[torch.dtype] = None) -> nn.Module: """Move model to target device with optional dtype conversion.""" target_device = get_device(device) model = model.to(target_device) if dtype is not None: model = model.to(dtype) return model
def memory_stats() -> Dict[str, float]: """Return current GPU memory usage in GB.""" if not torch.cuda.is_available(): return {} return { "allocated_gb": torch.cuda.memory_allocated() / (1024 ** 3), "reserved_gb": torch.cuda.memory_reserved() / (1024 ** 3), "max_allocated_gb": torch.cuda.max_memory_allocated() / (1024 ** 3), }
def clear_cache(): """Clear GPU memory cache.""" if torch.cuda.is_available(): torch.cuda.empty_cache()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129"""===================================== Shulker Code — Quantization Module INT8 / INT4 model quantization Developed by @kopeedev / CyeroX=====================================
Quantization reduces model size and speeds up CPU inference:- INT8: ~2x smaller, ~1.5x faster, minimal quality loss- INT4: ~4x smaller, ~2x faster, some quality loss
On CPU devices with limited RAM, always use INT8 quantization."""
import torchimport torch.nn as nnfrom typing import Optional
def quantize_model_int8(model: nn.Module) -> nn.Module: """ Apply dynamic INT8 quantization to a model. Works on CPU only. Replaces Linear layers with INT8 versions.
Args: model: The model to quantize
Returns: Quantized model (in-place + returned) """ print("⚙️ Applying INT8 dynamic quantization...") model = torch.quantization.quantize_dynamic( model, qconfig_spec={nn.Linear}, # Quantize only Linear layers dtype=torch.qint8, ) print("✅ INT8 quantization applied") return model
def quantize_model_int4(model: nn.Module, device: str = "auto") -> nn.Module: """ Apply 4-bit quantization using bitsandbytes library. Supports both CPU and CUDA.
Requires: pip install bitsandbytes
Args: model: The model to quantize device: Target device
Returns: 4-bit quantized model """ try: import bitsandbytes as bnb from transformers import BitsAndBytesConfig except ImportError: print("⚠️ bitsandbytes not found. Falling back to INT8 quantization.") return quantize_model_int8(model)
print("⚙️ Applying INT4 quantization (bitsandbytes)...")
# Replace Linear layers with 4-bit versions for name, module in model.named_modules(): if isinstance(module, nn.Linear) and module.weight.numel() > 4096: # Replace with 4-bit linear parent_name = ".".join(name.split(".")[:-1]) child_name = name.split(".")[-1] parent = dict(model.named_modules()).get(parent_name, model)
try: quant_layer = bnb.nn.Linear4bit( module.in_features, module.out_features, bias=module.bias is not None, compute_dtype=torch.bfloat16, compress_statistics=True, quant_type="nf4", # NF4: better quality than int4 ) quant_layer.weight = bnb.nn.Params4bit( module.weight.data, requires_grad=False, quant_type="nf4", ) setattr(parent, child_name, quant_layer) except Exception as e: # Skip layers that can't be quantized pass
print("✅ INT4 (NF4) quantization applied") return model
def estimate_model_size(num_params: int, dtype: str = "float32") -> float: """ Estimate model size in GB.
Args: num_params: Number of parameters dtype: "float32" (4B), "float16"/"bfloat16" (2B), "int8" (1B), "int4" (0.5B)
Returns: Size in GB """ bytes_per_param = { "float32": 4, "float16": 2, "bfloat16": 2, "int8": 1, "int4": 0.5, }.get(dtype, 4)
size_bytes = num_params * bytes_per_param return size_bytes / (1024 ** 3)
def print_model_size(model: nn.Module, name: str = "Model"): """Print model parameter count and size estimates.""" num_params = sum(p.numel() for p in model.parameters()) trainable = sum(p.numel() for p in model.parameters() if p.requires_grad)
print(f"\n📊 {name} Size Report:") print(f" Total params: {num_params:>15,}") print(f" Trainable params: {trainable:>15,}") print(f" FP32 size: {estimate_model_size(num_params, 'float32'):>10.2f} GB") print(f" FP16 size: {estimate_model_size(num_params, 'float16'):>10.2f} GB") print(f" INT8 size: {estimate_model_size(num_params, 'int8'):>10.2f} GB") print(f" INT4 size: {estimate_model_size(num_params, 'int4'):>10.2f} GB")utils/__init__.pyAdded+1
utils/banner.pyAdded+130
utils/hardware.pyAdded+202
utils/quantization.pyAdded+129