Laura Wagner commited on
Commit ·
6ce312c
1
Parent(s): 0b5c83f
added local inference code
Browse files
jupyter_notebooks/Section_2-3-4_Figure_8_deepfake_adapters.ipynb
CHANGED
|
@@ -1665,43 +1665,7 @@
|
|
| 1665 |
"cell_type": "markdown",
|
| 1666 |
"id": "01086b35",
|
| 1667 |
"metadata": {},
|
| 1668 |
-
"source":
|
| 1669 |
-
"## Qwen-2.5-32B Local Annotation (Ollama)\n",
|
| 1670 |
-
"\n",
|
| 1671 |
-
"Run **Qwen-2.5-32B-Instruct** locally using Ollama - NO API COSTS!\n",
|
| 1672 |
-
"\n",
|
| 1673 |
-
"**Requirements:**\n",
|
| 1674 |
-
"- Ollama installed: https://ollama.com/\n",
|
| 1675 |
-
"- GPU: NVIDIA A100 80GB (recommended)\n",
|
| 1676 |
-
"- RAM: 265GB system RAM\n",
|
| 1677 |
-
"- Model cache: `data/models/` (auto-downloaded on first run)\n",
|
| 1678 |
-
"- Model size: ~20GB download\n",
|
| 1679 |
-
"- VRAM usage: ~22-25GB during inference\n",
|
| 1680 |
-
"\n",
|
| 1681 |
-
"**Setup:**\n",
|
| 1682 |
-
"```bash\n",
|
| 1683 |
-
"# 1. Install Ollama (if not installed)\n",
|
| 1684 |
-
"curl -fsSL https://ollama.com/install.sh | sh\n",
|
| 1685 |
-
"\n",
|
| 1686 |
-
"# 2. Pull Qwen-2.5-32B-Instruct\n",
|
| 1687 |
-
"ollama pull qwen2.5:32b-instruct\n",
|
| 1688 |
-
"\n",
|
| 1689 |
-
"# 3. Verify model is available\n",
|
| 1690 |
-
"ollama list\n",
|
| 1691 |
-
"```\n",
|
| 1692 |
-
"\n",
|
| 1693 |
-
"**Advantages:**\n",
|
| 1694 |
-
"- ✅ FREE - No API costs\n",
|
| 1695 |
-
"- ✅ Fast - Local inference on A100\n",
|
| 1696 |
-
"- ✅ Privacy - Data never leaves your machine\n",
|
| 1697 |
-
"- ✅ Offline - Works without internet\n",
|
| 1698 |
-
"- ✅ High quality - 32B parameter model\n",
|
| 1699 |
-
"\n",
|
| 1700 |
-
"**Performance:**\n",
|
| 1701 |
-
"- Speed: ~5-10 tokens/sec on A100\n",
|
| 1702 |
-
"- Throughput: ~100-200 samples/hour (depends on prompt length)\n",
|
| 1703 |
-
"- Cost: $0 (after model download)"
|
| 1704 |
-
]
|
| 1705 |
},
|
| 1706 |
{
|
| 1707 |
"cell_type": "code",
|
|
@@ -1709,226 +1673,7 @@
|
|
| 1709 |
"id": "5dd7a803",
|
| 1710 |
"metadata": {},
|
| 1711 |
"outputs": [],
|
| 1712 |
-
"source": [
|
| 1713 |
-
"import pandas as pd\n",
|
| 1714 |
-
"import json\n",
|
| 1715 |
-
"import time\n",
|
| 1716 |
-
"import re\n",
|
| 1717 |
-
"import subprocess\n",
|
| 1718 |
-
"from pathlib import Path\n",
|
| 1719 |
-
"from tqdm import tqdm\n",
|
| 1720 |
-
"\n",
|
| 1721 |
-
"current_dir = Path.cwd()\n",
|
| 1722 |
-
"input_file = current_dir.parent / \"data/CSV/NER_POI_step02_annotated.csv\"\n",
|
| 1723 |
-
"\n",
|
| 1724 |
-
"# === CONFIGURATION ===\n",
|
| 1725 |
-
"TEST_MODE = True\n",
|
| 1726 |
-
"TEST_SIZE = 10\n",
|
| 1727 |
-
"MAX_ROWS = 20000\n",
|
| 1728 |
-
"SAVE_INTERVAL = 10\n",
|
| 1729 |
-
"\n",
|
| 1730 |
-
"# Ollama settings\n",
|
| 1731 |
-
"MODEL_NAME = \"qwen2.5:32b-instruct\" # or \"qwen2.5:32b\" for base model\n",
|
| 1732 |
-
"OLLAMA_HOST = \"http://localhost:11434\" # Default Ollama port\n",
|
| 1733 |
-
"\n",
|
| 1734 |
-
"PROFESSION_CATEGORIES = [\n",
|
| 1735 |
-
" \"actor\", \"adult performer\", \"singer/musician\", \"model\",\n",
|
| 1736 |
-
" \"online personality\", \"public figure\", \"voice actor/ASMR\",\n",
|
| 1737 |
-
" \"sports professional\", \"tv personality\"\n",
|
| 1738 |
-
"]\n",
|
| 1739 |
-
"\n",
|
| 1740 |
-
"# === CHECK OLLAMA ===\n",
|
| 1741 |
-
"def check_ollama():\n",
|
| 1742 |
-
" \"\"\"Check if Ollama is installed and model is available.\"\"\"\n",
|
| 1743 |
-
" try:\n",
|
| 1744 |
-
" result = subprocess.run(\n",
|
| 1745 |
-
" [\"ollama\", \"list\"],\n",
|
| 1746 |
-
" capture_output=True,\n",
|
| 1747 |
-
" text=True,\n",
|
| 1748 |
-
" timeout=5\n",
|
| 1749 |
-
" )\n",
|
| 1750 |
-
" \n",
|
| 1751 |
-
" if result.returncode == 0:\n",
|
| 1752 |
-
" print(\"✅ Ollama is installed\")\n",
|
| 1753 |
-
" \n",
|
| 1754 |
-
" # Check if model is available\n",
|
| 1755 |
-
" if MODEL_NAME in result.stdout or \"qwen2.5\" in result.stdout:\n",
|
| 1756 |
-
" print(f\"✅ Model {MODEL_NAME} is available\")\n",
|
| 1757 |
-
" return True\n",
|
| 1758 |
-
" else:\n",
|
| 1759 |
-
" print(f\"⚠️ Model {MODEL_NAME} not found\")\n",
|
| 1760 |
-
" print(f\" Run: ollama pull {MODEL_NAME}\")\n",
|
| 1761 |
-
" return False\n",
|
| 1762 |
-
" else:\n",
|
| 1763 |
-
" print(\"❌ Ollama command failed\")\n",
|
| 1764 |
-
" return False\n",
|
| 1765 |
-
" except FileNotFoundError:\n",
|
| 1766 |
-
" print(\"❌ Ollama not installed\")\n",
|
| 1767 |
-
" print(\" Install: curl -fsSL https://ollama.com/install.sh | sh\")\n",
|
| 1768 |
-
" return False\n",
|
| 1769 |
-
" except Exception as e:\n",
|
| 1770 |
-
" print(f\"❌ Error checking Ollama: {e}\")\n",
|
| 1771 |
-
" return False\n",
|
| 1772 |
-
"\n",
|
| 1773 |
-
"# Check Ollama before proceeding\n",
|
| 1774 |
-
"if not check_ollama():\n",
|
| 1775 |
-
" raise RuntimeError(\"Ollama not ready. Please install Ollama and pull the model.\")\n",
|
| 1776 |
-
"\n",
|
| 1777 |
-
"# === LOAD DATA ===\n",
|
| 1778 |
-
"df = pd.read_csv(input_file)\n",
|
| 1779 |
-
"print(f\"\\nLoaded {len(df)} rows\")\n",
|
| 1780 |
-
"\n",
|
| 1781 |
-
"if TEST_MODE:\n",
|
| 1782 |
-
" print(f\"Running in TEST MODE with {TEST_SIZE} samples\")\n",
|
| 1783 |
-
" df = df.head(TEST_SIZE).copy()\n",
|
| 1784 |
-
"elif MAX_ROWS:\n",
|
| 1785 |
-
" df = df.head(MAX_ROWS).copy()\n",
|
| 1786 |
-
"\n",
|
| 1787 |
-
"# === CREATE PROMPT ===\n",
|
| 1788 |
-
"def create_prompt(name: str, tags: list, country: str) -> str:\n",
|
| 1789 |
-
" tags_str = \", \".join(tags[:5]) if tags else \"none\"\n",
|
| 1790 |
-
" country_str = country if country else \"unknown\"\n",
|
| 1791 |
-
" \n",
|
| 1792 |
-
" return f\"\"\"You are an expert at identifying public figures.\n",
|
| 1793 |
-
"\n",
|
| 1794 |
-
"Given: Name: {name}, Tags: {tags_str}, Country: {country_str}\n",
|
| 1795 |
-
"\n",
|
| 1796 |
-
"Provide in JSON format:\n",
|
| 1797 |
-
"{{\n",
|
| 1798 |
-
" \"full_name\": \"<full name>\",\n",
|
| 1799 |
-
" \"gender\": \"<Male/Female/Other/Unknown>\",\n",
|
| 1800 |
-
" \"professions\": [\"<profession 1>\", \"<profession 2>\", \"<profession 3>\"],\n",
|
| 1801 |
-
" \"country\": \"<country>\"\n",
|
| 1802 |
-
"}}\n",
|
| 1803 |
-
"\n",
|
| 1804 |
-
"Choose professions ONLY from: {\", \".join(PROFESSION_CATEGORIES)}\n",
|
| 1805 |
-
"- Max 3 professions, ordered by relevance\n",
|
| 1806 |
-
"- \"online personality\" includes streamers, cosplayers, influencers\n",
|
| 1807 |
-
"- Return \"Unknown\" if uncertain\n",
|
| 1808 |
-
"\n",
|
| 1809 |
-
"Return ONLY JSON, no extra text.\"\"\"\n",
|
| 1810 |
-
"\n",
|
| 1811 |
-
"# === QUERY QWEN LOCAL ===\n",
|
| 1812 |
-
"def query_qwen_local(prompt: str) -> dict:\n",
|
| 1813 |
-
" \"\"\"Query Qwen-2.5-32B via Ollama.\"\"\"\n",
|
| 1814 |
-
" for attempt in range(3):\n",
|
| 1815 |
-
" try:\n",
|
| 1816 |
-
" result = subprocess.run(\n",
|
| 1817 |
-
" [\n",
|
| 1818 |
-
" \"ollama\", \"run\", MODEL_NAME,\n",
|
| 1819 |
-
" prompt\n",
|
| 1820 |
-
" ],\n",
|
| 1821 |
-
" capture_output=True,\n",
|
| 1822 |
-
" text=True,\n",
|
| 1823 |
-
" timeout=60 # 60 second timeout per query\n",
|
| 1824 |
-
" )\n",
|
| 1825 |
-
" \n",
|
| 1826 |
-
" if result.returncode == 0:\n",
|
| 1827 |
-
" content = result.stdout.strip()\n",
|
| 1828 |
-
" \n",
|
| 1829 |
-
" # Parse JSON from response\n",
|
| 1830 |
-
" json_match = re.search(r'\\{[^}]+\\}', content, re.DOTALL)\n",
|
| 1831 |
-
" if json_match:\n",
|
| 1832 |
-
" return json.loads(json_match.group())\n",
|
| 1833 |
-
" \n",
|
| 1834 |
-
" # If no JSON found, try to extract from markdown code block\n",
|
| 1835 |
-
" code_block = re.search(r'```(?:json)?\\s*({[^}]+})\\s*```', content, re.DOTALL)\n",
|
| 1836 |
-
" if code_block:\n",
|
| 1837 |
-
" return json.loads(code_block.group(1))\n",
|
| 1838 |
-
" \n",
|
| 1839 |
-
" return None\n",
|
| 1840 |
-
" \n",
|
| 1841 |
-
" except subprocess.TimeoutExpired:\n",
|
| 1842 |
-
" print(f\"Qwen local timeout (attempt {attempt+1})\")\n",
|
| 1843 |
-
" if attempt < 2:\n",
|
| 1844 |
-
" time.sleep(2)\n",
|
| 1845 |
-
" except json.JSONDecodeError as e:\n",
|
| 1846 |
-
" print(f\"Qwen local JSON error (attempt {attempt+1}): {e}\")\n",
|
| 1847 |
-
" if attempt < 2:\n",
|
| 1848 |
-
" time.sleep(1)\n",
|
| 1849 |
-
" except Exception as e:\n",
|
| 1850 |
-
" print(f\"Qwen local error (attempt {attempt+1}): {e}\")\n",
|
| 1851 |
-
" if attempt < 2:\n",
|
| 1852 |
-
" time.sleep(2)\n",
|
| 1853 |
-
" \n",
|
| 1854 |
-
" return None\n",
|
| 1855 |
-
"\n",
|
| 1856 |
-
"# === PROCESS ===\n",
|
| 1857 |
-
"output_file = current_dir.parent / f\"data/CSV/qwen_local_annotated_POI{'_test' if TEST_MODE else ''}.csv\"\n",
|
| 1858 |
-
"index_file = current_dir.parent / \"misc/qwen_local_query_index.txt\"\n",
|
| 1859 |
-
"\n",
|
| 1860 |
-
"current_index = 0\n",
|
| 1861 |
-
"if index_file.exists():\n",
|
| 1862 |
-
" with open(index_file) as f:\n",
|
| 1863 |
-
" current_index = int(f.read().strip())\n",
|
| 1864 |
-
"\n",
|
| 1865 |
-
"for col in ['full_name', 'gender', 'profession_llm', 'country']:\n",
|
| 1866 |
-
" if col not in df.columns:\n",
|
| 1867 |
-
" df[col] = 'Unknown'\n",
|
| 1868 |
-
"\n",
|
| 1869 |
-
"print(f\"\\nAnnotating with QWEN-2.5-32B LOCAL - rows {current_index} to {len(df)}...\")\n",
|
| 1870 |
-
"print(f\"Model: {MODEL_NAME}\")\n",
|
| 1871 |
-
"print(f\"This may take a while (~100-200 samples/hour on A100)\\n\")\n",
|
| 1872 |
-
"\n",
|
| 1873 |
-
"try:\n",
|
| 1874 |
-
" start_time = time.time()\n",
|
| 1875 |
-
" \n",
|
| 1876 |
-
" for i in tqdm(range(current_index, len(df)), desc=\"Qwen Local\"):\n",
|
| 1877 |
-
" row = df.iloc[i]\n",
|
| 1878 |
-
" \n",
|
| 1879 |
-
" tags = [str(row[f'tag_{j}']).lower() for j in range(1, 8)\n",
|
| 1880 |
-
" if f'tag_{j}' in row and pd.notna(row[f'tag_{j}'])]\n",
|
| 1881 |
-
" \n",
|
| 1882 |
-
" prompt = create_prompt(\n",
|
| 1883 |
-
" row.get('real_name', row.get('name', '')),\n",
|
| 1884 |
-
" tags,\n",
|
| 1885 |
-
" row.get('likely_country', '')\n",
|
| 1886 |
-
" )\n",
|
| 1887 |
-
" \n",
|
| 1888 |
-
" result = query_qwen_local(prompt)\n",
|
| 1889 |
-
" \n",
|
| 1890 |
-
" if result:\n",
|
| 1891 |
-
" df.at[i, 'full_name'] = result.get('full_name', 'Unknown')\n",
|
| 1892 |
-
" df.at[i, 'gender'] = result.get('gender', 'Unknown')\n",
|
| 1893 |
-
" profs = result.get('professions', [])\n",
|
| 1894 |
-
" df.at[i, 'profession_llm'] = \", \".join(profs[:3]) if isinstance(profs, list) else str(profs)\n",
|
| 1895 |
-
" df.at[i, 'country'] = result.get('country', 'Unknown')\n",
|
| 1896 |
-
" \n",
|
| 1897 |
-
" current_index = i + 1\n",
|
| 1898 |
-
" \n",
|
| 1899 |
-
" if (i + 1) % SAVE_INTERVAL == 0 or (i + 1) == len(df):\n",
|
| 1900 |
-
" df.to_csv(output_file, index=False)\n",
|
| 1901 |
-
" with open(index_file, 'w') as f:\n",
|
| 1902 |
-
" f.write(str(current_index))\n",
|
| 1903 |
-
" \n",
|
| 1904 |
-
" # Calculate stats\n",
|
| 1905 |
-
" elapsed = time.time() - start_time\n",
|
| 1906 |
-
" samples_done = i + 1 - (current_index - (i + 1))\n",
|
| 1907 |
-
" samples_per_hour = (samples_done / elapsed) * 3600 if elapsed > 0 else 0\n",
|
| 1908 |
-
" \n",
|
| 1909 |
-
" print(f\"✅ Saved after {i+1} rows (~{samples_per_hour:.1f} samples/hour)\")\n",
|
| 1910 |
-
" \n",
|
| 1911 |
-
" elapsed_total = time.time() - start_time\n",
|
| 1912 |
-
" print(f\"\\n✅ Done! Results: {output_file}\")\n",
|
| 1913 |
-
" print(f\"Total time: {elapsed_total/60:.1f} minutes\")\n",
|
| 1914 |
-
" print(f\"Average speed: {len(df)/(elapsed_total/3600):.1f} samples/hour\")\n",
|
| 1915 |
-
" \n",
|
| 1916 |
-
" print(f\"\\nTop professions:\\n{df['profession_llm'].value_counts().head(10)}\")\n",
|
| 1917 |
-
"\n",
|
| 1918 |
-
"except KeyboardInterrupt:\n",
|
| 1919 |
-
" print(f\"\\n⚠️ Interrupted by user\")\n",
|
| 1920 |
-
" df.to_csv(output_file, index=False)\n",
|
| 1921 |
-
" with open(index_file, 'w') as f:\n",
|
| 1922 |
-
" f.write(str(current_index))\n",
|
| 1923 |
-
" print(f\"Progress saved up to row {current_index}\")\n",
|
| 1924 |
-
"\n",
|
| 1925 |
-
"except Exception as e:\n",
|
| 1926 |
-
" print(f\"⚠️ Error: {e}\")\n",
|
| 1927 |
-
" df.to_csv(output_file, index=False)\n",
|
| 1928 |
-
" with open(index_file, 'w') as f:\n",
|
| 1929 |
-
" f.write(str(current_index))\n",
|
| 1930 |
-
" print(f\"Progress saved up to row {current_index}\")"
|
| 1931 |
-
]
|
| 1932 |
}
|
| 1933 |
],
|
| 1934 |
"metadata": {
|
|
@@ -1938,4 +1683,4 @@
|
|
| 1938 |
},
|
| 1939 |
"nbformat": 4,
|
| 1940 |
"nbformat_minor": 5
|
| 1941 |
-
}
|
|
|
|
| 1665 |
"cell_type": "markdown",
|
| 1666 |
"id": "01086b35",
|
| 1667 |
"metadata": {},
|
| 1668 |
+
"source": "## Qwen-2.5-32B Local Annotation (Hugging Face Transformers)\n\nRun **Qwen-2.5-32B-Instruct** locally using Hugging Face Transformers - NO API COSTS!\n\n**Requirements:**\n- GPU: NVIDIA A100 80GB or similar (32B model needs ~60-70GB VRAM)\n- RAM: 128GB+ system RAM recommended\n- Model cache: `data/models/` (auto-downloaded on first run)\n- Model size: ~65GB download (BF16 weights)\n\n**Installation:**\n```bash\n# Install required packages\npip install torch transformers accelerate\n```\n\n**Advantages:**\n- ✅ FREE - No API costs\n- ✅ Fast - Local inference with GPU acceleration\n- ✅ Privacy - Data never leaves your machine\n- ✅ Offline - Works without internet (after download)\n- ✅ High quality - 32B parameter instruction-tuned model\n\n**Performance:**\n- Speed: ~10-30 tokens/sec on A100 (depends on batch size)\n- Throughput: ~200-500 samples/hour\n- Cost: $0 (after model download)\n\n**Model Info:**\n- HuggingFace: `Qwen/Qwen2.5-32B-Instruct`\n- License: Apache 2.0 (commercial use allowed)\n- Context: 32K tokens"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1669 |
},
|
| 1670 |
{
|
| 1671 |
"cell_type": "code",
|
|
|
|
| 1673 |
"id": "5dd7a803",
|
| 1674 |
"metadata": {},
|
| 1675 |
"outputs": [],
|
| 1676 |
+
"source": "import pandas as pd\nimport json\nimport time\nimport re\nfrom pathlib import Path\nfrom tqdm import tqdm\nimport torch\nfrom transformers import AutoModelForCausalLM, AutoTokenizer\n\ncurrent_dir = Path.cwd()\ninput_file = current_dir.parent / \"data/CSV/NER_POI_step02_annotated.csv\"\n\n# === CONFIGURATION ===\nTEST_MODE = True\nTEST_SIZE = 10\nMAX_ROWS = 20000\nSAVE_INTERVAL = 10\n\n# Model settings\nMODEL_NAME = \"Qwen/Qwen2.5-32B-Instruct\"\nCACHE_DIR = current_dir.parent / \"data/models\"\nCACHE_DIR.mkdir(parents=True, exist_ok=True)\n\nPROFESSION_CATEGORIES = [\n \"actor\", \"adult performer\", \"singer/musician\", \"model\",\n \"online personality\", \"public figure\", \"voice actor/ASMR\",\n \"sports professional\", \"tv personality\"\n]\n\n# === LOAD MODEL ===\nprint(f\"Loading model: {MODEL_NAME}\")\nprint(f\"Cache directory: {CACHE_DIR}\")\nprint(f\"This may take a while on first run (~65GB download)...\\n\")\n\n# Check GPU availability\ndevice = \"cuda\" if torch.cuda.is_available() else \"cpu\"\nprint(f\"Device: {device}\")\n\nif device == \"cpu\":\n print(\"⚠️ WARNING: No GPU detected! Inference will be VERY slow.\")\n print(\" Consider using a GPU or reducing model size.\")\n\n# Load tokenizer\nprint(\"Loading tokenizer...\")\ntokenizer = AutoTokenizer.from_pretrained(\n MODEL_NAME,\n cache_dir=str(CACHE_DIR),\n trust_remote_code=True\n)\nprint(\"✅ Tokenizer loaded\")\n\n# Load model with optimizations\nprint(\"Loading model (this may take several minutes)...\")\nmodel = AutoModelForCausalLM.from_pretrained(\n MODEL_NAME,\n cache_dir=str(CACHE_DIR),\n torch_dtype=torch.bfloat16, # Use BF16 for efficiency\n device_map=\"auto\", # Automatically distribute across GPUs\n trust_remote_code=True\n)\nmodel.eval() # Set to evaluation mode\nprint(\"✅ Model loaded\")\n\n# Check VRAM usage\nif torch.cuda.is_available():\n vram_gb = torch.cuda.max_memory_allocated() / 1024**3\n print(f\"VRAM used: {vram_gb:.2f} GB\\n\")\n\n# === LOAD DATA ===\ndf = pd.read_csv(input_file)\nprint(f\"Loaded {len(df)} rows\")\n\nif TEST_MODE:\n print(f\"Running in TEST MODE with {TEST_SIZE} samples\")\n df = df.head(TEST_SIZE).copy()\nelif MAX_ROWS:\n df = df.head(MAX_ROWS).copy()\n\n# === CREATE PROMPT ===\ndef create_prompt(name: str, tags: list, country: str) -> str:\n tags_str = \", \".join(tags[:5]) if tags else \"none\"\n country_str = country if country else \"unknown\"\n \n return f\"\"\"You are an expert at identifying public figures.\n\nGiven: Name: {name}, Tags: {tags_str}, Country: {country_str}\n\nProvide in JSON format:\n{{\n \"full_name\": \"<full name>\",\n \"gender\": \"<Male/Female/Other/Unknown>\",\n \"professions\": [\"<profession 1>\", \"<profession 2>\", \"<profession 3>\"],\n \"country\": \"<country>\"\n}}\n\nChoose professions ONLY from: {\", \".join(PROFESSION_CATEGORIES)}\n- Max 3 professions, ordered by relevance\n- \"online personality\" includes streamers, cosplayers, influencers\n- Return \"Unknown\" if uncertain\n\nReturn ONLY JSON, no extra text.\"\"\"\n\n# === QUERY QWEN LOCAL ===\ndef query_qwen_local(prompt: str) -> dict:\n \"\"\"Query Qwen-2.5-32B locally via transformers.\"\"\"\n try:\n # Format as chat message\n messages = [\n {\"role\": \"user\", \"content\": prompt}\n ]\n \n # Tokenize\n text = tokenizer.apply_chat_template(\n messages,\n tokenize=False,\n add_generation_prompt=True\n )\n \n inputs = tokenizer([text], return_tensors=\"pt\").to(device)\n \n # Generate\n with torch.no_grad():\n outputs = model.generate(\n **inputs,\n max_new_tokens=512,\n temperature=0.1,\n do_sample=True,\n top_p=0.9,\n pad_token_id=tokenizer.eos_token_id\n )\n \n # Decode\n generated_ids = outputs[0][inputs['input_ids'].shape[1]:]\n response = tokenizer.decode(generated_ids, skip_special_tokens=True)\n \n # Parse JSON from response\n json_match = re.search(r'\\{[^}]+\\}', response, re.DOTALL)\n if json_match:\n return json.loads(json_match.group())\n \n # Try markdown code block\n code_block = re.search(r'```(?:json)?\\s*(\\{[^}]+\\})\\s*```', response, re.DOTALL)\n if code_block:\n return json.loads(code_block.group(1))\n \n return None\n \n except json.JSONDecodeError as e:\n print(f\"JSON parse error: {e}\")\n return None\n except Exception as e:\n print(f\"Generation error: {e}\")\n return None\n\n# === PROCESS ===\noutput_file = current_dir.parent / f\"data/CSV/qwen_local_annotated_POI{'_test' if TEST_MODE else ''}.csv\"\nindex_file = current_dir.parent / \"misc/qwen_local_query_index.txt\"\n\ncurrent_index = 0\nif index_file.exists():\n with open(index_file) as f:\n current_index = int(f.read().strip())\n print(f\"Resuming from index {current_index}\")\n\nfor col in ['full_name', 'gender', 'profession_llm', 'country']:\n if col not in df.columns:\n df[col] = 'Unknown'\n\nprint(f\"\\nAnnotating with QWEN-2.5-32B LOCAL - rows {current_index} to {len(df)}...\")\nprint(f\"Model: {MODEL_NAME}\")\nprint(f\"This may take a while (~200-500 samples/hour on A100)\\n\")\n\ntry:\n start_time = time.time()\n \n for i in tqdm(range(current_index, len(df)), desc=\"Qwen Local\"):\n row = df.iloc[i]\n \n tags = [str(row[f'tag_{j}']).lower() for j in range(1, 8)\n if f'tag_{j}' in row and pd.notna(row[f'tag_{j}'])]\n \n prompt = create_prompt(\n row.get('real_name', row.get('name', '')),\n tags,\n row.get('likely_country', '')\n )\n \n result = query_qwen_local(prompt)\n \n if result:\n df.at[i, 'full_name'] = result.get('full_name', 'Unknown')\n df.at[i, 'gender'] = result.get('gender', 'Unknown')\n profs = result.get('professions', [])\n df.at[i, 'profession_llm'] = \", \".join(profs[:3]) if isinstance(profs, list) else str(profs)\n df.at[i, 'country'] = result.get('country', 'Unknown')\n \n current_index = i + 1\n \n if (i + 1) % SAVE_INTERVAL == 0 or (i + 1) == len(df):\n df.to_csv(output_file, index=False)\n with open(index_file, 'w') as f:\n f.write(str(current_index))\n \n # Calculate stats\n elapsed = time.time() - start_time\n samples_done = current_index - (0 if not index_file.exists() else int(open(index_file).read().strip()))\n samples_per_hour = (samples_done / elapsed) * 3600 if elapsed > 0 else 0\n \n print(f\"✅ Saved after {i+1} rows (~{samples_per_hour:.1f} samples/hour)\")\n \n elapsed_total = time.time() - start_time\n print(f\"\\n✅ Done! Results: {output_file}\")\n print(f\"Total time: {elapsed_total/60:.1f} minutes\")\n print(f\"Average speed: {len(df)/(elapsed_total/3600):.1f} samples/hour\")\n \n print(f\"\\nTop professions:\\n{df['profession_llm'].value_counts().head(10)}\")\n \n # Show VRAM stats\n if torch.cuda.is_available():\n print(f\"\\nFinal VRAM usage: {torch.cuda.max_memory_allocated() / 1024**3:.2f} GB\")\n\nexcept KeyboardInterrupt:\n print(f\"\\n⚠️ Interrupted by user\")\n df.to_csv(output_file, index=False)\n with open(index_file, 'w') as f:\n f.write(str(current_index))\n print(f\"Progress saved up to row {current_index}\")\n\nexcept Exception as e:\n print(f\"⚠️ Error: {e}\")\n df.to_csv(output_file, index=False)\n with open(index_file, 'w') as f:\n f.write(str(current_index))\n print(f\"Progress saved up to row {current_index}\")"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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