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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
+
import torch
|
| 3 |
+
import torch.nn.functional as F
|
| 4 |
+
from torch import nn
|
| 5 |
+
from transformers import AutoTokenizer
|
| 6 |
+
from huggingface_hub import hf_hub_download
|
| 7 |
+
import os
|
| 8 |
+
|
| 9 |
+
# NOTE: For this to work in deployment, you MUST copy the 'retnet.py'
|
| 10 |
+
# file from the cloned repository's 'src' directory into your project root.
|
| 11 |
+
try:
|
| 12 |
+
from retnet import RetNet
|
| 13 |
+
except ImportError:
|
| 14 |
+
st.error("FATAL: The custom 'retnet.py' module is missing. Please copy it into the app's root directory.")
|
| 15 |
+
st.stop()
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
# --- 1. Hugging Face Setup and Constants ---
|
| 19 |
+
HF_MODEL_REPO_ID = "sebastiancgeorge/Retnet_coder"
|
| 20 |
+
MODEL_FILE = "model.pt"
|
| 21 |
+
MAX_LEN = 128
|
| 22 |
+
HIDDEN_DIM = 512
|
| 23 |
+
HEADS = 8
|
| 24 |
+
FFN_SIZE = HIDDEN_DIM * 4
|
| 25 |
+
LAYERS = 6
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
# --- 2. Model Loading and Caching ---
|
| 29 |
+
|
| 30 |
+
# @st.cache_resource is essential to prevent reloading the model on every interaction
|
| 31 |
+
@st.cache_resource
|
| 32 |
+
def load_model_and_tokenizer(model_repo_id):
|
| 33 |
+
"""Loads all model components from the Hugging Face Hub."""
|
| 34 |
+
|
| 35 |
+
try:
|
| 36 |
+
# Load Tokenizer
|
| 37 |
+
tokenizer = AutoTokenizer.from_pretrained("microsoft/codebert-base")
|
| 38 |
+
if tokenizer.pad_token is None:
|
| 39 |
+
tokenizer.pad_token = tokenizer.eos_token
|
| 40 |
+
vocab_size = len(tokenizer)
|
| 41 |
+
except Exception as e:
|
| 42 |
+
st.error(f"Error loading tokenizer: {e}")
|
| 43 |
+
return None, None, None, None, None
|
| 44 |
+
|
| 45 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 46 |
+
|
| 47 |
+
# Initialize Model Components
|
| 48 |
+
embedding = nn.Embedding(vocab_size, HIDDEN_DIM)
|
| 49 |
+
output_proj = nn.Linear(HIDDEN_DIM, vocab_size, bias=False)
|
| 50 |
+
output_proj.weight = embedding.weight # Tie weights
|
| 51 |
+
|
| 52 |
+
model = RetNet(
|
| 53 |
+
layers=LAYERS,
|
| 54 |
+
hidden_dim=HIDDEN_DIM,
|
| 55 |
+
ffn_size=FFN_SIZE,
|
| 56 |
+
heads=HEADS,
|
| 57 |
+
double_v_dim=False
|
| 58 |
+
)
|
| 59 |
+
|
| 60 |
+
# Download and Load Checkpoint
|
| 61 |
+
try:
|
| 62 |
+
st.info(f"Downloading model weights from {model_repo_id}...")
|
| 63 |
+
model_path = hf_hub_download(repo_id=model_repo_id, filename=MODEL_FILE)
|
| 64 |
+
|
| 65 |
+
checkpoint = torch.load(model_path, map_location=device)
|
| 66 |
+
|
| 67 |
+
model.load_state_dict(checkpoint['model_state'])
|
| 68 |
+
embedding.load_state_dict(checkpoint['embedding_state'])
|
| 69 |
+
output_proj.load_state_dict(checkpoint['output_proj_state'])
|
| 70 |
+
|
| 71 |
+
model.to(device).eval()
|
| 72 |
+
embedding.to(device).eval()
|
| 73 |
+
output_proj.to(device).eval()
|
| 74 |
+
st.success("Model loaded successfully!")
|
| 75 |
+
|
| 76 |
+
except Exception as e:
|
| 77 |
+
st.error(f"Error loading checkpoint from Hugging Face Hub. Error: {e}")
|
| 78 |
+
return None, None, None, None, None
|
| 79 |
+
|
| 80 |
+
return model, embedding, output_proj, tokenizer, device
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
# --- 3. Inference Function (Code Generation) ---
|
| 84 |
+
|
| 85 |
+
def generate_code(prompt, model, embedding, output_proj, tokenizer, device, max_length=50, temperature=0.8, top_k=50):
|
| 86 |
+
"""Generates code completion using the RetNet model."""
|
| 87 |
+
|
| 88 |
+
# Set to eval mode again for safety
|
| 89 |
+
model.eval()
|
| 90 |
+
|
| 91 |
+
tokens = tokenizer(prompt, return_tensors="pt", truncation=True, max_length=MAX_LEN//2)
|
| 92 |
+
input_ids = tokens["input_ids"].to(device)
|
| 93 |
+
|
| 94 |
+
generated = input_ids.clone()
|
| 95 |
+
prompt_length = generated.shape[1]
|
| 96 |
+
|
| 97 |
+
with torch.no_grad():
|
| 98 |
+
for _ in range(max_length):
|
| 99 |
+
current_input = generated if generated.shape[1] <= MAX_LEN else generated[:, -MAX_LEN:]
|
| 100 |
+
|
| 101 |
+
embeds = embedding(current_input)
|
| 102 |
+
outputs = model(embeds) # Parallel forward pass for generation
|
| 103 |
+
|
| 104 |
+
logits = output_proj(outputs[:, -1, :])
|
| 105 |
+
|
| 106 |
+
# Sampling
|
| 107 |
+
logits = logits / temperature
|
| 108 |
+
if top_k > 0:
|
| 109 |
+
v, _ = torch.topk(logits, top_k)
|
| 110 |
+
logits[logits < v[..., -1, None]] = float('-inf')
|
| 111 |
+
|
| 112 |
+
probs = F.softmax(logits, dim=-1)
|
| 113 |
+
if torch.isnan(probs).any() or probs.sum() == 0:
|
| 114 |
+
break
|
| 115 |
+
|
| 116 |
+
next_token = torch.multinomial(probs, num_samples=1)
|
| 117 |
+
|
| 118 |
+
if next_token.item() in [tokenizer.eos_token_id, tokenizer.pad_token_id]:
|
| 119 |
+
break
|
| 120 |
+
|
| 121 |
+
generated = torch.cat([generated, next_token], dim=1)
|
| 122 |
+
|
| 123 |
+
generated_tokens = generated[0, prompt_length:]
|
| 124 |
+
if len(generated_tokens) == 0:
|
| 125 |
+
return "[Model generated nothing new]"
|
| 126 |
+
|
| 127 |
+
text = tokenizer.decode(generated_tokens, skip_special_tokens=True)
|
| 128 |
+
return text.strip() if text.strip() else "[Empty generation]"
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
# --- 4. Streamlit UI Layout ---
|
| 132 |
+
st.set_page_config(page_title="RetNet Code Generation Demo", layout="wide")
|
| 133 |
+
|
| 134 |
+
st.title("🐍 RetNet Code Generation Demo")
|
| 135 |
+
st.markdown(f"""
|
| 136 |
+
Code generator powered by the Retentive Network model: **`{HF_MODEL_REPO_ID}`**.
|
| 137 |
+
""")
|
| 138 |
+
|
| 139 |
+
# Load model components
|
| 140 |
+
model, embedding, output_proj, tokenizer, device = load_model_and_tokenizer(HF_MODEL_REPO_ID)
|
| 141 |
+
|
| 142 |
+
if model is None:
|
| 143 |
+
st.stop()
|
| 144 |
+
|
| 145 |
+
# Sidebar for Parameters
|
| 146 |
+
st.sidebar.header("Generation Parameters")
|
| 147 |
+
max_len = st.sidebar.slider("Max Length", min_value=10, max_value=256, value=60, step=10)
|
| 148 |
+
temperature = st.sidebar.slider("Temperature", min_value=0.1, max_value=2.0, value=0.75, step=0.05)
|
| 149 |
+
top_k = st.sidebar.slider("Top K Sampling", min_value=0, max_value=100, value=50, step=5)
|
| 150 |
+
st.sidebar.caption(f"Running on device: **{device}**")
|
| 151 |
+
|
| 152 |
+
# Main Input Area
|
| 153 |
+
st.subheader("Enter your Code Prompt:")
|
| 154 |
+
prompt = st.text_area(
|
| 155 |
+
"Code Prompt",
|
| 156 |
+
value="def compute_mean_average(data_list):\n # Calculate the sum of all elements in the list\n",
|
| 157 |
+
height=150,
|
| 158 |
+
key="prompt_input"
|
| 159 |
+
)
|
| 160 |
+
|
| 161 |
+
if st.button("🚀 Generate Code", type="primary", use_container_width=True):
|
| 162 |
+
if not prompt:
|
| 163 |
+
st.warning("Please enter a code prompt to begin generation.")
|
| 164 |
+
else:
|
| 165 |
+
st.divider()
|
| 166 |
+
st.markdown("### 🤖 Generated Code:")
|
| 167 |
+
with st.spinner("Generating..."):
|
| 168 |
+
try:
|
| 169 |
+
result = generate_code(
|
| 170 |
+
prompt,
|
| 171 |
+
model,
|
| 172 |
+
embedding,
|
| 173 |
+
output_proj,
|
| 174 |
+
tokenizer,
|
| 175 |
+
device,
|
| 176 |
+
max_length=max_len,
|
| 177 |
+
temperature=temperature,
|
| 178 |
+
top_k=top_k
|
| 179 |
+
)
|
| 180 |
+
|
| 181 |
+
# Display the prompt and the generated completion
|
| 182 |
+
full_output = prompt + result
|
| 183 |
+
st.code(full_output, language='python')
|
| 184 |
+
|
| 185 |
+
except Exception as e:
|
| 186 |
+
st.error(f"An error occurred during generation: {e}")
|
| 187 |
+
|
| 188 |
+
st.divider()
|
| 189 |
+
st.caption(f"Model: {HF_MODEL_REPO_ID}")
|