"""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")