{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "397d74dc-36fc-4470-996c-30184f83dcfe", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Total samples: 1930\n", "Training samples: 1737 (90%)\n", "Validation samples: 193 (10%)\n", "Successfully created 'sft_train.jsonl' and 'sft_val.jsonl'.\n" ] } ], "source": [ "import json\n", "import random\n", "import os\n", "\n", "# --- Configuration ---\n", "input_filename = \"Inputfrm.json\"\n", "train_output_filename = \"sft_train.jsonl\"\n", "val_output_filename = \"sft_val.jsonl\"\n", "train_split_ratio = 0.9 # 80% for training, 20% for validation\n", "\n", "# --- Load data from input file ---\n", "data = []\n", "if not os.path.exists(input_filename):\n", " print(f\"Error: Input file '{input_filename}' not found.\")\n", " print(\"Please make sure 'Inputfrm.json' is in the same directory as the script, or provide its correct path.\")\n", " # Exit gracefully if the input file is missing\n", " exit(1)\n", "\n", "try:\n", " with open(input_filename, 'r', encoding='utf-8') as f:\n", " content = f.read()\n", " if not content.strip():\n", " print(f\"Warning: Input file '{input_filename}' is empty. No data to split.\")\n", " # Create empty output files if input is empty\n", " with open(train_output_filename, 'w', encoding='utf-8') as tf: pass\n", " with open(val_output_filename, 'w', encoding='utf-8') as vf: pass\n", " exit(0)\n", " \n", " # Assuming the input JSON file contains a list of objects\n", " data = json.loads(content)\n", " \n", " # Basic check: if data is not a list, print a warning and try to proceed if possible\n", " if not isinstance(data, list):\n", " print(f\"Warning: The content of '{input_filename}' is not a JSON list.\")\n", " print(\"Attempting to treat it as a single item or assuming it might be structured differently.\")\n", " # If it's a single object, wrap it in a list for consistency\n", " if isinstance(data, dict):\n", " data = [data]\n", " else:\n", " print(\"Error: Data is not a list or a dictionary. Cannot proceed with splitting.\")\n", " exit(1)\n", "\n", "except json.JSONDecodeError:\n", " print(f\"Error: Could not decode JSON from '{input_filename}'. Please check the file format.\")\n", " exit(1)\n", "except Exception as e:\n", " print(f\"An unexpected error occurred while reading the file: {e}\")\n", " exit(1)\n", "\n", "if not data:\n", " print(\"No data found in the input file after loading. Creating empty output files.\")\n", " with open(train_output_filename, 'w', encoding='utf-8') as tf: pass\n", " with open(val_output_filename, 'w', encoding='utf-8') as vf: pass\n", " exit(0)\n", "\n", "# --- Shuffle the data ---\n", "# Create a copy to shuffle to maintain original order if needed elsewhere\n", "shuffled_data = list(data)\n", "random.shuffle(shuffled_data)\n", "\n", "# --- Split the data ---\n", "total_samples = len(shuffled_data)\n", "num_train_samples = int(total_samples * train_split_ratio)\n", "\n", "train_data = shuffled_data[:num_train_samples]\n", "val_data = shuffled_data[num_train_samples:]\n", "\n", "print(f\"Total samples: {total_samples}\")\n", "print(f\"Training samples: {len(train_data)} ({train_split_ratio*100:.0f}%)\")\n", "print(f\"Validation samples: {len(val_data)} ({ (1-train_split_ratio)*100:.0f}%)\")\n", "\n", "# --- Write to output files in JSON Lines format ---\n", "try:\n", " with open(train_output_filename, 'w', encoding='utf-8') as train_f:\n", " for item in train_data:\n", " # json.dumps converts a Python object into a JSON string\n", " # writing each object as a separate line makes it JSON Lines format\n", " json.dump(item, train_f)\n", " train_f.write('\\n') # Add newline character for JSON Lines\n", "\n", " with open(val_output_filename, 'w', encoding='utf-8') as val_f:\n", " for item in val_data:\n", " json.dump(item, val_f)\n", " val_f.write('\\n') # Add newline character for JSON Lines\n", "\n", " print(f\"Successfully created '{train_output_filename}' and '{val_output_filename}'.\")\n", "\n", "except Exception as e:\n", " print(f\"An error occurred while writing to the output files: {e}\")\n", " exit(1)" ] }, { "cell_type": "code", "execution_count": null, "id": "14ba0cb7", "metadata": {}, "outputs": [ { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "ca2c617d7dd9409185885673e184aec7", "version_major": 2, "version_minor": 0 }, "text/plain": [ "Downloading bytes: | 0.00B " ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "e289c16527984d4a808157e2968b8100", "version_major": 2, "version_minor": 0 }, "text/plain": [ "Reconstructing (incomplete total...): | | 0.00B / 0.00B " ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "44188eaa53e543789a27dce55aa04c82", "version_major": 2, "version_minor": 0 }, "text/plain": [ "Fetching 27 files: 0%| | 0/27 [00:00\", OUT)\n", "PY\n", "\n", "\n", "python - <<'PY'\n", "import os\n", "import glob\n", "import shutil\n", "import torch\n", "from transformers import AutoModelForCausalLM, AutoTokenizer\n", "from peft import PeftModel\n", "from safetensors.torch import save_file\n", "\n", "ORIGINAL_BASE = \"/models/nemotron3-nano-base\"\n", "CPT_MERGED = \"/models/nemotron3-nano-cpt-merged\"\n", "ADAPTER = \"/checkpoints/sft/epoch_14_step_44/model\"\n", "OUT = \"/models/nemotron3-nano-sft-final\"\n", "\n", "# 1. Copy original dynamic python modules to CPT merged directory if missing\n", "for py_file in glob.glob(os.path.join(ORIGINAL_BASE, \"*.py\")):\n", " shutil.copy(py_file, CPT_MERGED)\n", "\n", "os.makedirs(OUT, exist_ok=True)\n", "\n", "# 2. Load model and tokenizer\n", "tok = AutoTokenizer.from_pretrained(CPT_MERGED, trust_remote_code=True)\n", "model = AutoModelForCausalLM.from_pretrained(\n", " CPT_MERGED, dtype=torch.bfloat16, trust_remote_code=True, device_map=\"cpu\"\n", ")\n", "model = PeftModel.from_pretrained(model, ADAPTER)\n", "model = model.merge_and_unload()\n", "\n", "# 3. Save configs, tokenizer, and safetensors\n", "model.config.save_pretrained(OUT)\n", "tok.save_pretrained(OUT)\n", "save_file(model.state_dict(), os.path.join(OUT, \"model.safetensors\"))\n", "\n", "# 4. Copy custom dynamic module files to final output directory\n", "for py_file in glob.glob(os.path.join(ORIGINAL_BASE, \"*.py\")):\n", " shutil.copy(py_file, OUT)\n", "\n", "print(\"merged final SFT model ->\", OUT)\n", "PY\n" ] }, { "cell_type": "code", "execution_count": 16, "id": "9987388d", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Successfully logged out from all access tokens.\n" ] } ], "source": [ "# !hf auth login --token \n", "!hf auth logout" ] }, { "cell_type": "code", "execution_count": 11, "id": "d8e37407", "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "/home/zeus/miniconda3/envs/cloudspace/lib/python3.12/site-packages/huggingface_hub/hf_api.py:11691: UserWarning: Warnings while validating metadata in README.md:\n", "- empty or missing yaml metadata in repo card\n", " warnings.warn(f\"Warnings while validating metadata in README.md:\\n{message}\")\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Upload complete! Your model is at: https://huggingface.ai/AkshayPatil9028/Nemotron_3.5_Nano\n" ] } ], "source": [ "from huggingface_hub import HfApi, create_repo, upload_folder\n", "\n", "# --- Configuration ---\n", "# Replace with your Hugging Face username, desired repo name, and local model path\n", "your_hf_username = \"AkshayPatil9028\" # <-- !!! REPLACE THIS !!!\n", "model_repo_name = \"Nemotron_3.5_Nano\" # <-- !!! REPLACE THIS !!!\n", "local_model_path = \"Nemotron3.5_Nano\" # <-- !!! REPLACE THIS !!!\n", "\n", "# --- Script Logic ---\n", "repo_id = f\"{your_hf_username}/{model_repo_name}\"\n", "api = HfApi()\n", "\n", "try:\n", " # Create repo if it doesn't exist\n", " try:\n", " api.repo_info(repo_id=repo_id)\n", " except Exception:\n", " create_repo(repo_id=repo_id, repo_type=\"model\", private=True) # Set private=True for private repo\n", "\n", " # Upload folder\n", " upload_folder(repo_id=repo_id, folder_path=local_model_path)\n", " print(f\"Upload complete! Your model is at: https://huggingface.ai/{repo_id}\")\n", "\n", "except Exception as e:\n", " print(f\"Error: {e}\\nEnsure you are logged in (run `huggingface-cli login` in terminal).\")" ] }, { "cell_type": "code", "execution_count": null, "id": "2a0096ff", "metadata": {}, "outputs": [], "source": [ "mkdir -p ~/data ~/models ~/checkpoints ~/hf_cache ~/workspace/configs\n" ] }, { "cell_type": "code", "execution_count": null, "id": "ff829493", "metadata": {}, "outputs": [], "source": [ "import torch\n", "from transformers import AutoModelForCausalLM, AutoTokenizer\n", "\n", "MODEL_PATH = \"/models/nemotron3-nano-cpt-merged\"\n", "\n", "tokenizer = AutoTokenizer.from_pretrained(MODEL_PATH, trust_remote_code=True)\n", "model = AutoModelForCausalLM.from_pretrained(\n", " MODEL_PATH,\n", " dtype=torch.bfloat16,\n", " device_map=\"cuda\" if torch.cuda.is_available() else \"cpu\",\n", " trust_remote_code=True,\n", ")\n", "\n", "prompt = \"The key advantages of standardizing deep learning architectures are\"\n", "\n", "inputs = tokenizer(prompt, return_tensors=\"pt\").to(model.device)\n", "\n", "with torch.no_grad():\n", " outputs = model.generate(\n", " **inputs,\n", " max_new_tokens=150,\n", " temperature=0.7,\n", " top_p=0.9,\n", " do_sample=True,\n", " pad_token_id=tokenizer.eos_token_id,\n", " )\n", "\n", "response = tokenizer.decode(outputs[0], skip_special_tokens=True)\n", "print(\"=== CPT Output ===\")\n", "print(response)" ] }, { "cell_type": "code", "execution_count": null, "id": "a91978a7", "metadata": {}, "outputs": [], "source": [ "import torch\n", "from transformers import AutoModelForCausalLM, AutoTokenizer\n", "\n", "MODEL_PATH = \"/models/nemotron3-nano-sft-final\"\n", "\n", "tokenizer = AutoTokenizer.from_pretrained(MODEL_PATH, trust_remote_code=True)\n", "model = AutoModelForCausalLM.from_pretrained(\n", " MODEL_PATH,\n", " dtype=torch.bfloat16,\n", " device_map=\"cuda\" if torch.cuda.is_available() else \"cpu\",\n", " trust_remote_code=True,\n", ")\n", "\n", "messages = [\n", " {\"role\": \"system\", \"content\": \"You are a helpful and precise AI assistant.\"},\n", " {\"role\": \"user\", \"content\": \"Explain why adapter merging is beneficial for LLM deployment.\"},\n", "]\n", "\n", "# Apply Nemotron chat template\n", "if hasattr(tokenizer, \"apply_chat_template\") and tokenizer.chat_template:\n", " prompt = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)\n", "else:\n", " # Fallback chat formatting if template is absent\n", " prompt = f\"<|im_start|>system\\n{messages[0]['content']}<|im_end|>\\n<|im_start|>user\\n{messages[1]['content']}<|im_end|>\\n<|im_start|>assistant\\n\"\n", "\n", "inputs = tokenizer(prompt, return_tensors=\"pt\").to(model.device)\n", "\n", "with torch.no_grad():\n", " outputs = model.generate(\n", " **inputs,\n", " max_new_tokens=256,\n", " temperature=0.3,\n", " top_p=0.95,\n", " do_sample=True,\n", " pad_token_id=tokenizer.eos_token_id,\n", " )\n", "\n", "# Slice output to decode only generated tokens (excluding prompt)\n", "generated_tokens = outputs[0][inputs.input_ids.shape[-1] :]\n", "response = tokenizer.decode(generated_tokens, skip_special_tokens=True)\n", "\n", "print(\"=== SFT Output ===\")\n", "print(response)" ] }, { "cell_type": "code", "execution_count": null, "id": "4ba8edab", "metadata": {}, "outputs": [], "source": [ "from huggingface_hub import HfApi, create_repo, upload_file\n", "\n", "# --- Configuration ---\n", "# 1. Your Hugging Face username\n", "# Replace 'your-username' with your actual Hugging Face username.\n", "your_hf_username = \"Akshay9028\" # <-- !!! REPLACE THIS !!!\n", "\n", "# 2. The desired name for your model repository on Hugging Face.\n", "# This will be the name of the new repo on your Hugging Face account.\n", "# e.g., 'my-awesome-llm', 'my-image-classifier'\n", "model_repo_name = \"NotWorking\" # <-- !!! REPLACE THIS !!!\n", "\n", "# 3. The local path to the specific file you want to upload.\n", "# e.g., './my_model/config.json', './tokenizer.json'\n", "local_file_path = \"Untitled.ipynb\" # <-- !!! REPLACE THIS !!!\n", "\n", "# 4. The desired name/path for the file *within* the Hugging Face repository.\n", "# This can be just the filename, or a path like 'config/config.json'\n", "# if you want to organize it in a subfolder.\n", "# If omitted, it uses the base name of local_file_path.\n", "file_in_repo_name = \"Code.ipynb\" # <-- !!! REPLACE THIS if you want it named differently or in a subfolder !!!\n", "\n", "# --- Script Logic ---\n", "repo_id = f\"{your_hf_username}/{model_repo_name}\"\n", "api = HfApi()\n", "\n", "try:\n", " # Check if the repository exists. If not, create it.\n", " try:\n", " api.repo_info(repo_id=repo_id)\n", " except Exception:\n", " print(f\"Repository '{repo_id}' not found. Creating new repository...\")\n", " create_repo(repo_id=repo_id, repo_type=\"model\", private=False) # Set private=True for private repo\n", " print(f\"Repository '{repo_id}' created successfully.\")\n", "\n", " # Upload the specific file\n", " print(f\"Uploading '{local_file_path}' to '{repo_id}' as '{file_in_repo_name}'...\")\n", " upload_file(\n", " repo_id=repo_id,\n", " path_or_fileobj=local_file_path,\n", " path_in_repo=file_in_repo_name,\n", " # Optional: add commit_message and revision if needed\n", " # commit_message=\"Add config file\",\n", " # revision=\"main\",\n", " )\n", " print(f\"\\nUpload complete! Your file is at: https://huggingface.ai/{repo_id}/blob/main/{file_in_repo_name}\")\n", "\n", "except Exception as e:\n", " print(f\"Error: {e}\\nEnsure you are logged in. Run `huggingface-cli login` in your terminal.\")" ] } ], "metadata": { "kernelspec": { "display_name": "cloudspace", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.12.11" } }, "nbformat": 4, "nbformat_minor": 5 }