{"cells":[{"cell_type":"markdown","metadata":{"id":"eEyPmvXoWIKv"},"source":["# Retrieval"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"nhDqmBOrWLZS"},"outputs":[],"source":["from transformers import LlavaForConditionalGeneration, BitsAndBytesConfig, AutoProcessor\n","import torch\n","\n","REPO_ID = \"codeShare/joycaption_beta_one_SDNQ\"\n","\n","bnb = BitsAndBytesConfig(\n"," load_in_4bit=True,\n"," bnb_4bit_compute_dtype=torch.float16,\n"," bnb_4bit_quant_type=\"nf4\"\n",")\n","\n","processor = AutoProcessor.from_pretrained(REPO_ID)\n","\n","model = LlavaForConditionalGeneration.from_pretrained(\n"," REPO_ID,\n"," quantization_config=bnb,\n"," device_map=\"auto\",\n"," trust_remote_code=True\n",")\n","\n","print(\"✅ Loaded BnB model correctly\")"]},{"cell_type":"markdown","metadata":{"id":"c0yCIbvJnRAL"},"source":["# Build bitsandbytes joycaption"]},{"cell_type":"code","execution_count":null,"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"elapsed":18049,"status":"ok","timestamp":1777063772430,"user":{"displayName":"gfuku63","userId":"10213382542081034600"},"user_tz":-120},"id":"58JPv1RKnUoz","outputId":"b468e32f-8cdf-44ea-f4de-fc1d505ba3e4"},"outputs":[{"name":"stdout","output_type":"stream","text":["Mounted at /content/drive\n","✅ Drive + HF login ready\n"]}],"source":["#@markdown ## 1 - Setup environment (clean install)\n","\n","from google.colab import drive, userdata\n","\n","drive.mount('/content/drive')\n","\n","hf_token = userdata.get(\"HF_TOKEN\")\n","\n","if hf_token:\n"," from huggingface_hub import login\n"," login(token=hf_token)\n","\n","print(\"✅ Drive + HF login ready\")"]},{"cell_type":"code","execution_count":null,"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"elapsed":20775,"status":"ok","timestamp":1777063793206,"user":{"displayName":"gfuku63","userId":"10213382542081034600"},"user_tz":-120},"id":"G9162XsznXiN","outputId":"db62e0fc-8dd0-42aa-b188-535e426ecbcd"},"outputs":[{"name":"stdout","output_type":"stream","text":["\u001b[?25l \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m0.0/104.0 kB\u001b[0m \u001b[31m?\u001b[0m eta \u001b[36m-:--:--\u001b[0m\r\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m104.0/104.0 kB\u001b[0m \u001b[31m4.8 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[?25h✅ Dependencies installed\n"]}],"source":["#@markdown ## 2 - Install correct dependencies (FIXED VERSIONS)\n","\n","#!pip uninstall -y transformers tokenizers -q\n","!pip install -U bitsandbytes>=0.46.1\n","\n","!pip install -q \\\n"," transformers \\\n"," tokenizers \\\n"," accelerate \\\n"," huggingface_hub \\\n"," safetensors \\\n"," sdnq\n","\n","print(\"✅ Dependencies installed\")"]},{"cell_type":"code","execution_count":null,"metadata":{"colab":{"base_uri":"https://localhost:8080/","height":141},"executionInfo":{"elapsed":75674,"status":"ok","timestamp":1777064919581,"user":{"displayName":"gfuku63","userId":"10213382542081034600"},"user_tz":-120},"id":"KcCPLGza85CX","outputId":"ea357645-88b0-438c-ed29-df2b0d09e70a"},"outputs":[{"data":{"application/vnd.jupyter.widget-view+json":{"model_id":"13b91d53f9f046b59250a9021b1d2a68","version_major":2,"version_minor":0},"text/plain":["Downloading (incomplete total...): 0.00B [00:00, ?B/s]"]},"metadata":{},"output_type":"display_data"},{"data":{"application/vnd.jupyter.widget-view+json":{"model_id":"4808039c604d47ac915d03eac5dfe0e4","version_major":2,"version_minor":0},"text/plain":["Fetching 4 files: 0%| | 0/4 [00:00=0.46.1\n","\n","!pip install -q \\\n"," transformers \\\n"," tokenizers \\\n"," accelerate \\\n"," huggingface_hub \\\n"," safetensors \\\n"," sdnq\n","\n","print(\"✅ Dependencies installed\")"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"_S6JR1AuXSxF"},"outputs":[],"source":["#@markdown ## 3 - Load 4bit model (temporary bootstrap – low VRAM)\n","import torch\n","from transformers import BitsAndBytesConfig, AutoProcessor, LlavaForConditionalGeneration\n","\n","MODEL_NAME = \"fancyfeast/llama-joycaption-beta-one-hf-llava\"\n","\n","bnb = BitsAndBytesConfig(\n"," load_in_4bit=True,\n"," bnb_4bit_compute_dtype=torch.float16,\n"," bnb_4bit_quant_type=\"nf4\"\n",")\n","\n","model = LlavaForConditionalGeneration.from_pretrained(\n"," MODEL_NAME,\n"," quantization_config=bnb,\n"," device_map=\"auto\", # temporary, will be moved to CPU immediately\n"," trust_remote_code=True\n",")\n","\n","processor = AutoProcessor.from_pretrained(MODEL_NAME)\n","\n","print(\"✅ Model loaded in 4bit (bootstrap only)\")"]},{"cell_type":"code","source":["#@markdown ## 4 - Low-RAM dequant + fast sharding (CPU-only + ROBUST resume)\n","\n","import os\n","import gc\n","import torch\n","import json\n","from safetensors.torch import save_file, load_file\n","import bitsandbytes.functional as F\n","\n","# ========================= CONFIG =========================\n","SHARD_DIR = \"/content/joycaption_dequant_shards\"\n","os.makedirs(SHARD_DIR, exist_ok=True)\n","\n","MAX_SHARD_SIZE_GB = 0.5\n","# =========================================================\n","\n","def _get_safetensors_keys(path):\n"," \"\"\"Ultra-reliable way to read keys from any safetensors file (no device=meta needed)\"\"\"\n"," try:\n"," with open(path, \"rb\") as f:\n"," length = int.from_bytes(f.read(8), \"little\")\n"," header = json.loads(f.read(length).decode(\"utf-8\"))\n"," # All keys except the internal __metadata__ block\n"," keys = [k for k in header.keys() if k != \"__metadata__\"]\n"," return keys\n"," except Exception as e:\n"," print(f\" ❌ Failed to parse header of {os.path.basename(path)}: {e}\")\n"," return []\n","\n","def get_processed_keys(shard_dir=SHARD_DIR):\n"," \"\"\"Scan shards WITHOUT loading any tensors\"\"\"\n"," processed = set()\n"," shard_files = sorted([f for f in os.listdir(shard_dir) if f.endswith(\".safetensors\")])\n","\n"," print(f\"🔍 Scanning {len(shard_files)} existing shards for already-processed layers...\")\n"," if not shard_files:\n"," print(\" → No shards found yet\")\n"," return processed\n","\n"," for shard_file in shard_files:\n"," path = os.path.join(shard_dir, shard_file)\n"," print(f\" Checking {shard_file}...\", end=\" \")\n"," keys = _get_safetensors_keys(path)\n"," if keys:\n"," print(f\"✅ {len(keys)} keys found\")\n"," processed.update(keys)\n"," else:\n"," print(\"⚠️ no keys parsed\")\n","\n"," print(f\"✅ Total processed keys detected: {len(processed)}\\n\")\n"," return processed\n","\n","def load_dequant_shards(model, shard_dir=SHARD_DIR):\n"," \"\"\"Load shards ONLY at the very end – forces CPU\"\"\"\n"," shard_files = sorted([f for f in os.listdir(shard_dir) if f.endswith(\".safetensors\")])\n"," if not shard_files:\n"," print(\"No shards found – starting from scratch\")\n"," return model\n","\n"," print(f\"🔄 Loading {len(shard_files)} dequant shards (CPU only)...\")\n"," model = model.cpu()\n"," torch.cuda.empty_cache()\n"," gc.collect()\n","\n"," for shard_file in shard_files:\n"," path = os.path.join(shard_dir, shard_file)\n"," state = load_file(path, device=\"cpu\")\n"," for key, tensor in state.items():\n"," try:\n"," submodule_name = \".\".join(key.split(\".\")[:-1])\n"," submodule = model.get_submodule(submodule_name)\n"," if hasattr(submodule, \"weight\"):\n"," submodule.weight = torch.nn.Parameter(tensor.to(torch.float16))\n"," print(f\" ✅ Restored {key}\")\n"," except Exception as e:\n"," print(f\" ⚠️ Could not restore {key}: {e}\")\n"," print(\"✅ All shards loaded on CPU\")\n"," return model\n","\n","def dequantize_model_to_fp16(model, shard_dir=SHARD_DIR, max_shard_gb=0.5):\n"," model = model.cpu()\n"," torch.cuda.empty_cache()\n"," gc.collect()\n","\n"," processed_keys = get_processed_keys(shard_dir)\n","\n"," cumulative_bytes = 0\n"," current_shard_dict = {}\n"," shard_id = len([f for f in os.listdir(shard_dir) if f.endswith(\".safetensors\")])\n","\n"," print(\"🚀 Starting CPU-only dequantization with immediate offloading...\")\n","\n"," for name, module in list(model.named_modules()):\n"," if not (hasattr(module, \"weight\") and module.weight is not None):\n"," continue\n"," if not hasattr(module.weight, \"quant_state\"):\n"," continue\n","\n"," key = name + \".weight\"\n"," if key in processed_keys:\n"," print(f\"⏭️ Skipping already processed: {name}\")\n"," continue\n","\n"," print(f\"Dequantizing: {name}\")\n","\n"," try:\n"," weight = module.weight\n"," quant_state = weight.quant_state\n","\n"," weight_cpu = weight.to(\"cpu\")\n"," del module.weight\n"," del weight\n"," torch.cuda.empty_cache()\n"," gc.collect()\n","\n"," dequant = F.dequantize_4bit(weight_cpu, quant_state)\n","\n"," module.weight = torch.nn.Parameter(dequant.to(torch.float16))\n","\n"," current_shard_dict[key] = module.weight.data.clone()\n"," layer_bytes = module.weight.numel() * module.weight.element_size()\n"," cumulative_bytes += layer_bytes\n","\n"," print(f\" → {layer_bytes / (1024**3):.3f} GB | cumulative {cumulative_bytes / (1024**3):.3f} GB\")\n","\n"," if cumulative_bytes / (1024**3) >= max_shard_gb:\n"," shard_path = os.path.join(shard_dir, f\"dequant_shard_{shard_id:05d}.safetensors\")\n"," save_file(current_shard_dict, shard_path)\n"," print(f\"💾 Saved shard → {shard_path} ({len(current_shard_dict)} keys)\")\n","\n"," # IMMEDIATE OFFLOAD\n"," for saved_key in list(current_shard_dict.keys()):\n"," try:\n"," sub_name = \".\".join(saved_key.split(\".\")[:-1])\n"," sub = model.get_submodule(sub_name)\n"," if hasattr(sub, \"weight\"):\n"," del sub.weight\n"," sub.weight = None\n"," except:\n"," pass\n","\n"," current_shard_dict = {}\n"," cumulative_bytes = 0\n"," shard_id += 1\n","\n"," del dequant\n"," del weight_cpu\n"," gc.collect()\n","\n"," except Exception as e:\n"," print(f\"❌ Skipped {name}: {e}\")\n"," gc.collect()\n","\n"," # final shard\n"," if current_shard_dict:\n"," shard_path = os.path.join(shard_dir, f\"dequant_shard_{shard_id:05d}.safetensors\")\n"," save_file(current_shard_dict, shard_path)\n"," print(f\"💾 Saved final shard → {shard_path}\")\n","\n"," for saved_key in list(current_shard_dict.keys()):\n"," try:\n"," sub_name = \".\".join(saved_key.split(\".\")[:-1])\n"," sub = model.get_submodule(sub_name)\n"," if hasattr(sub, \"weight\"):\n"," del sub.weight\n"," sub.weight = None\n"," except:\n"," pass\n","\n"," print(\"✅ Dequantization complete – all weights offloaded to disk\")\n"," return model"],"metadata":{"id":"EOZGbgp-p90C"},"execution_count":null,"outputs":[]},{"cell_type":"code","execution_count":null,"metadata":{"id":"XeDK_bTjafNo"},"outputs":[],"source":["#@markdown ## Run dequantization (Step 4)\n","# Resume + continue dequant (CPU only)\n","# ERROR! This function cant detect previously safed safetensors!\n","model = dequantize_model_to_fp16(model, SHARD_DIR, MAX_SHARD_SIZE_GB)\n","\n","# Now load everything back on CPU (this is where your previous VRAM OOM happened)\n","model = load_dequant_shards(model, SHARD_DIR)\n","\n","print(\"✅ Fully dequantized on CPU – ready for SDNQ\")"]},{"cell_type":"code","source":["import torch\n","import gc\n","\n","# Make sure the whole model (including any lingering CUDA tensors) is on CPU\n","model = model.to(\"cpu\")\n","torch.cuda.empty_cache()\n","gc.collect()\n","\n","print(\"✅ Model forced to CPU + cache cleared\")"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"2Brzp1uknwCj","executionInfo":{"status":"ok","timestamp":1777120263566,"user_tz":-120,"elapsed":513,"user":{"displayName":"Nnekos4Lyfe","userId":"11521490251288716219"}},"outputId":"bbac3636-e0c5-4733-e5e3-c796d24e40a3"},"execution_count":11,"outputs":[{"output_type":"stream","name":"stdout","text":["✅ Model forced to CPU + cache cleared\n"]}]},{"cell_type":"code","execution_count":12,"metadata":{"id":"FW5Ho-7hdEg9","colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"status":"ok","timestamp":1777120271551,"user_tz":-120,"elapsed":15,"user":{"displayName":"Nnekos4Lyfe","userId":"11521490251288716219"}},"outputId":"42f426b8-bd7d-460d-f703-010fe74232dc"},"outputs":[{"output_type":"stream","name":"stdout","text":["✅ Converted to SDNQ (fully on CPU)\n"]}],"source":["#@markdown ## 5 - Convert to SDNQ (CPU-only to avoid VRAM OOM)\n","\n","from sdnq import sdnq_post_load_quant\n","from sdnq.common import use_torch_compile as triton_is_available\n","\n","model = sdnq_post_load_quant(\n"," model,\n"," weights_dtype=\"uint4\",\n"," quantized_matmul_dtype=None,\n"," group_size=0,\n"," svd_rank=32,\n"," svd_steps=8,\n"," dynamic_loss_threshold=None,\n"," use_svd=False,\n"," quant_conv=False,\n"," quant_embedding=False,\n"," use_quantized_matmul=triton_is_available,\n"," use_quantized_matmul_conv=False,\n"," use_dynamic_quantization=False,\n"," dequantize_fp32=True,\n"," non_blocking=False,\n"," add_skip_keys=True,\n"," quantization_device=\"cuda\",\n"," return_device=\"cpu\",\n"," modules_to_not_convert=[\"correction_coefs\", \"prediction_coefs\", \"lm_head\", \"embedding_projection\"],\n"," modules_dtype_dict={\"int8\": [\"lm_head\"]},\n"," modules_quant_config={\"embed_tokens_per_layer\": {\"quantization_device\": \"cpu\"}},\n",")\n","\n","print(\"✅ Converted to SDNQ (fully on CPU)\")"]},{"cell_type":"code","source":["import torch\n","import gc\n","\n","# Make sure the whole model (including any lingering CUDA tensors) is on CPU\n","model = model.to(\"cpu\")\n","torch.cuda.empty_cache()\n","gc.collect()\n","\n","print(\"✅ Model forced to CPU + cache cleared\")"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"RBoPsEW9n2g3","executionInfo":{"status":"ok","timestamp":1777120405179,"user_tz":-120,"elapsed":430,"user":{"displayName":"Nnekos4Lyfe","userId":"11521490251288716219"}},"outputId":"5baca558-b256-4158-aba4-a8009eaac641"},"execution_count":16,"outputs":[{"output_type":"stream","name":"stdout","text":["✅ Model forced to CPU + cache cleared\n"]}]},{"cell_type":"code","source":["save_dir = \"/content/llava_sdnq_clean\"\n","\n","model.save_pretrained(\n"," save_dir,\n"," max_shard_size=\"2GB\", # or \"2GB\" / \"5GB\" — play with this\n"," safe_serialization=True # safetensors is preferred for SDNQ inference models\n",")\n","\n","processor.save_pretrained(save_dir)\n","print(\"✅ SDNQ model saved with sharding\")"],"metadata":{"id":"R3w8Q8zDoCrj"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":["# Upload"],"metadata":{"id":"NSilAeopmfuj"}},{"cell_type":"code","execution_count":null,"metadata":{"id":"RLWikdYVDCFA"},"outputs":[],"source":["#@markdown ## 7 - Upload to HuggingFace\n","\n","from huggingface_hub import HfApi, upload_folder\n","\n","repo_id = \"codeShare/joycaption_beta_one_SDNQ\" #@param {type:\"string\"}\n","\n","api = HfApi(token=hf_token)\n","api.create_repo(repo_id=repo_id, repo_type=\"model\", exist_ok=True)\n","\n","upload_folder(\n"," folder_path=save_dir,\n"," repo_id=repo_id,\n"," repo_type=\"model\"\n",")\n","\n","print(\"✅ Uploaded SDNQ model\")"]},{"cell_type":"markdown","source":["# Save dequants to hub + retrieve"],"metadata":{"id":"0zanwSrGliYC"}},{"cell_type":"code","source":["#@markdown ## Upload dequant shards to HF repo (codeShare/dequantized-workspace)\n","\n","from huggingface_hub import HfApi, create_repo\n","\n","REPO_ID = \"codeShare/dequantized-workspace\"\n","\n","# Create repo if it doesn't exist yet\n","try:\n"," create_repo(REPO_ID, exist_ok=True, private=False) # change private=True if you want\n"," print(f\"✅ Repo {REPO_ID} ready\")\n","except Exception as e:\n"," print(f\"Repo already exists or error: {e}\")\n","\n","api = HfApi()\n","\n","print(\"📤 Uploading all dequant shards...\")\n","api.upload_folder(\n"," folder_path=SHARD_DIR,\n"," repo_id=REPO_ID,\n"," repo_type=\"model\",\n"," allow_patterns=\"dequant_shard_*.safetensors\",\n"," delete_patterns=\"*\" # optional: replace old files if re-uploading\n",")\n","\n","print(f\"✅ All shards uploaded → https://huggingface.co/{REPO_ID}\")"],"metadata":{"id":"hjLwWSRClsRl"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["#@markdown ## Re-assemble dequantized model from HF repo (new session)\n","\n","# 1. Run your normal Step 1 + Step 2 + Step 3 (4-bit bootstrap)\n","\n","# 2. Download shards from HF\n","import os\n","from huggingface_hub import snapshot_download\n","\n","SHARD_DIR = \"/content/joycaption_dequant_shards\"\n","os.makedirs(SHARD_DIR, exist_ok=True)\n","\n","print(\"📥 Downloading dequantized FP16 shards from HF...\")\n","snapshot_download(\n"," repo_id=\"codeShare/dequantized-workspace\",\n"," local_dir=SHARD_DIR,\n"," allow_patterns=[\"*.safetensors\"],\n"," tqdm_enabled=True\n",")\n","print(\"✅ Shards downloaded\")\n","\n","# 3. Paste the three functions from the updated Step 4 above:\n","# - get_processed_keys\n","# - load_dequant_shards\n","# - dequantize_model_to_fp16\n","# (you only need load_dequant_shards for re-assembly)\n","\n","# 4. Load shards into the model\n","model = load_dequant_shards(model, SHARD_DIR)\n","\n","print(\"✅ Model fully reassembled from HF shards on CPU – ready for SDNQ\")"],"metadata":{"cellView":"form","id":"xAViU9o1lmE-"},"execution_count":null,"outputs":[]}],"metadata":{"accelerator":"GPU","colab":{"collapsed_sections":["eEyPmvXoWIKv","c0yCIbvJnRAL","0zanwSrGliYC"],"gpuType":"T4","provenance":[{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/build joycap sdnq.ipynb","timestamp":1777110475920}]},"kernelspec":{"display_name":"Python 3","name":"python3"},"language_info":{"name":"python"}},"nbformat":4,"nbformat_minor":0}