Spaces:
Sleeping
Sleeping
Download test_rag_cuda.py from SirBallsXIV/DNN-Project: direct link, hf CLI and curl.
- Browser
- Download file 4.99 kB
-
https://huggingface.co/spaces/SirBallsXIV/DNN-Project/resolve/main/test_rag_cuda.py
- Command line
-
hf download hf://spaces/SirBallsXIV/DNN-Project/test_rag_cuda.py
-
curl -L -o test_rag_cuda.py https://huggingface.co/spaces/SirBallsXIV/DNN-Project/resolve/main/test_rag_cuda.py
4.99 kB
| """Test RAG + LoRA for CUDA kernel generation - uses ACTUAL vectorstore""" | |
| import torch | |
| from transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig | |
| from peft import PeftModel | |
| from pathlib import Path | |
| # RAG imports | |
| from langchain_community.embeddings import SentenceTransformerEmbeddings | |
| from langchain_community.vectorstores import Chroma | |
| print("=" * 60) | |
| print("π RAG-Enhanced CUDA Kernel Generation Test") | |
| print("=" * 60) | |
| # Paths - same as before (base_model) | |
| BASE_MODEL = Path("./base_model") | |
| LORA = Path("./Qwen_7B_Cuda") | |
| VECTORSTORE_DIR = Path("./backend/vectorstore") | |
| # Load vectorstore | |
| print("\nπ Loading CUDA documentation vectorstore...") | |
| embeddings = SentenceTransformerEmbeddings( | |
| model_name="sentence-transformers/all-MiniLM-L6-v2", | |
| model_kwargs={'device': 'cuda' if torch.cuda.is_available() else 'cpu'} | |
| ) | |
| vectorstore = Chroma( | |
| persist_directory=str(VECTORSTORE_DIR), | |
| embedding_function=embeddings, | |
| collection_name="cuda_docs" | |
| ) | |
| print(f"β Loaded {vectorstore._collection.count()} document chunks") | |
| # Load model | |
| print("\nπ€ Loading LLM with LoRA adapter...") | |
| tokenizer = AutoTokenizer.from_pretrained(str(BASE_MODEL)) | |
| model = AutoModelForCausalLM.from_pretrained( | |
| str(BASE_MODEL), | |
| device_map="auto", | |
| torch_dtype=torch.float16, | |
| ) | |
| model = PeftModel.from_pretrained(model, str(LORA)) | |
| print("β Model loaded!") | |
| # Test prompt - ask for unified memory and streams (RAG should look this up) | |
| prompt = "Explain how to safely use CUDA unified memory (cudaMallocManaged) in a multi-GPU setup with CUDA streams, and provide a basic code example." | |
| print("\n" + "=" * 60) | |
| print(f"π USER PROMPT: {prompt}") | |
| print("=" * 60) | |
| # RAG lookup - query the vectorstore for actual CUDA docs | |
| print("\nπ RAG: Querying CUDA documentation for unified memory APIs...") | |
| rag_results = vectorstore.similarity_search(prompt, k=5) | |
| if rag_results: | |
| print(f"\nπ Retrieved {len(rag_results)} relevant chunks from CUDA docs:") | |
| for i, doc in enumerate(rag_results, 1): | |
| source = doc.metadata.get('source', 'Unknown')[:50] | |
| content_preview = doc.page_content[:150].replace('\n', ' ') | |
| print(f" [{i}] {source}...: \"{content_preview}...\"") | |
| # Build RAG context from retrieved docs | |
| rag_context = "\n\n".join([doc.page_content for doc in rag_results]) | |
| else: | |
| rag_context = "" | |
| print("β οΈ No relevant docs found in vectorstore") | |
| # Build system prompt with ACTUAL RAG context (not hardcoded!) | |
| SYSTEM_PROMPT = f"""You are an expert CUDA C++ developer and an authoritative source on the NVIDIA CUDA 13.1 Programming Guide. | |
| ## Retrieved CUDA 13.1 Documentation: | |
| {rag_context if rag_context else "No specific documentation found for this topic."} | |
| ## Instructions for Code Generation & Explanation: | |
| - ALWAYS base your answers on the provided documentation if available. | |
| - Write modern, highly-optimized, and safe CUDA C++ code. | |
| - Avoid deprecated APIs; use the latest supported functions (e.g., sync variants for warp-level operations). | |
| - If writing kernels, ensure proper memory alignment, coalesced memory accesses, and optimal block/grid configurations. | |
| - Provide step-by-step explanations for complex memory management, synchronizations, or group operations. | |
| - If the documentation doesn't cover something and you are unsure, clearly state your limitations. | |
| """ | |
| # Build messages | |
| messages = [ | |
| {"role": "system", "content": SYSTEM_PROMPT}, | |
| {"role": "user", "content": prompt} | |
| ] | |
| # Build full prompt using chat template | |
| full_prompt = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True) | |
| # Generate | |
| inputs = tokenizer(full_prompt, return_tensors="pt").to(model.device) | |
| # Get correct stop tokens (base eos + <|im_end|>) | |
| stop_tokens = [tokenizer.eos_token_id] | |
| if "<|im_end|>" in tokenizer.vocab: | |
| stop_tokens.append(tokenizer.vocab["<|im_end|>"]) | |
| print("\nβ‘ Generating response with RAG context injected...") | |
| with torch.no_grad(): | |
| outputs = model.generate( | |
| **inputs, | |
| max_new_tokens=512, | |
| do_sample=True, | |
| temperature=0.5, | |
| top_p=0.9, | |
| repetition_penalty=1.05, | |
| pad_token_id=tokenizer.pad_token_id or tokenizer.eos_token_id, | |
| eos_token_id=stop_tokens, | |
| ) | |
| response = tokenizer.decode(outputs[0][inputs['input_ids'].shape[1]:], skip_special_tokens=True) | |
| print("\n" + "=" * 60) | |
| print("π€ GENERATED RESPONSE (with RAG guidance):") | |
| print("=" * 60) | |
| print(response[:2000]) | |
| print("=" * 60) | |
| # Syntax check - verify it matches what was retrieved | |
| print("\nπ VERIFICATION:") | |
| print(f" RAG retrieved {len(rag_results)} chunks for guidance") | |
| print(f" Response uses RAG context: {'β Yes' if rag_context else 'β No'}") | |
| # Save response | |
| with open("test_rag_output.cu", "w") as f: | |
| f.write(response) | |
| print("\nπΎ Saved to test_rag_output.cu") |