mployd-engineering commited on
Commit
f00668e
·
verified ·
1 Parent(s): f13eeea

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +40 -23
app.py CHANGED
@@ -1,35 +1,46 @@
1
  import gradio as gr
2
  import torch
3
- from transformers import AutoModelForCausalLM, AutoTokenizer
4
- from peft import PeftModel
5
  import os
 
 
6
  from accelerate import Accelerator
7
 
8
  # --- Model Configuration ---
9
  # The LoRA adapter model on the Hugging Face Hub
10
  LORA_MODEL_ID = "LlamaFactoryAI/cv-job-description-matching"
11
- # The base model it was fine-tuned from (found in the model card)
12
  BASE_MODEL_ID = "akjindal53244/Llama-3.1-Storm-8B"
13
 
14
- # --- Model Loading ---
15
  try:
16
  print(f"Loading base model: {BASE_MODEL_ID}...")
17
 
18
  # 1. Load the BASE model
19
  base_model = AutoModelForCausalLM.from_pretrained(
20
  BASE_MODEL_ID,
21
- torch_dtype=torch.bfloat16, # Recommended dtype for Llama models
22
- device_map="auto" # Use accelerate to manage device placement
23
  )
24
 
25
  # 2. Load the base model's tokenizer
26
  tokenizer = AutoTokenizer.from_pretrained(BASE_MODEL_ID)
27
 
28
- # 3. Load the LoRA adapter weights on top of the base model
29
- model = PeftModel.from_pretrained(base_model, LORA_MODEL_ID)
 
 
 
 
 
 
 
30
 
31
- # 4. Merge the LoRA weights into the base model (for faster inference)
32
  model = model.merge_and_unload()
 
 
 
 
33
  print("LoRA adapter merged and model ready successfully.")
34
 
35
  except Exception as e:
@@ -37,13 +48,13 @@ except Exception as e:
37
  # Re-raise the exception to crash the space if loading fails
38
  raise
39
 
40
- # 5. Define the Prediction/Matching Function
41
  def match_cv_jd(cv_text: str, job_description_text: str):
42
  """
43
- Constructs the chat prompt, tokenizes, runs the LLM, and extracts the JSON output.
44
  """
45
  try:
46
- # Define the exact prompt structure used for fine-tuning (from model card)
47
  messages = [
48
  {"role": "system", "content": """
49
  You will receive a CV and a job description. Your task is to output a structured JSON format
@@ -58,33 +69,39 @@ def match_cv_jd(cv_text: str, job_description_text: str):
58
  messages,
59
  add_generation_prompt=True,
60
  return_tensors="pt"
61
- ).to(model.device) # Move to the correct device
62
 
63
  # Generate the response
64
  outputs = model.generate(
65
  inputs,
66
  max_new_tokens=512,
67
  do_sample=False,
68
- pad_token_id=tokenizer.eos_token_id # Important for generation
69
  )
70
 
71
  # Decode the generated text and clean up the prompt
72
- generated_text = tokenizer.decode(outputs[0], skip_special_tokens=True)
 
 
 
 
73
 
74
- # Extract the assistant's response (assuming the output starts after the user's prompt)
75
- assistant_response_start = generated_text.rfind("assistant\n")
76
  if assistant_response_start != -1:
77
- raw_json_output = generated_text[assistant_response_start + len("assistant\n"):].strip()
 
78
  else:
 
79
  raw_json_output = generated_text
80
 
81
- # For display, just return the raw text output
82
- return f"### Model Output (JSON format expected):\n\n```json\n{raw_json_output}\n```"
 
 
83
 
84
  except Exception as e:
85
- return f"An error occurred during prediction: {e}. If the model is too large, consider upgrading hardware."
86
 
87
- # 6. Create the Gradio Interface
88
  demo = gr.Interface(
89
  fn=match_cv_jd,
90
  inputs=[
@@ -93,7 +110,7 @@ demo = gr.Interface(
93
  ],
94
  outputs="markdown",
95
  title="LlamaFactory CV-Job Matching Demo",
96
- description=f"Interactive demo for the {LORA_MODEL_ID} model (LoRA on {BASE_MODEL_ID})."
97
  )
98
 
99
  if __name__ == "__main__":
 
1
  import gradio as gr
2
  import torch
 
 
3
  import os
4
+ from transformers import AutoModelForCausalLM, AutoTokenizer
5
+ from peft import PeftModel, PeftConfig # PeftConfig is essential for the fix
6
  from accelerate import Accelerator
7
 
8
  # --- Model Configuration ---
9
  # The LoRA adapter model on the Hugging Face Hub
10
  LORA_MODEL_ID = "LlamaFactoryAI/cv-job-description-matching"
11
+ # The base model it was fine-tuned from (Llama-3.1-Storm-8B)
12
  BASE_MODEL_ID = "akjindal53244/Llama-3.1-Storm-8B"
13
 
14
+ # --- Model Loading (CRITICAL SECTION) ---
15
  try:
16
  print(f"Loading base model: {BASE_MODEL_ID}...")
17
 
18
  # 1. Load the BASE model
19
  base_model = AutoModelForCausalLM.from_pretrained(
20
  BASE_MODEL_ID,
21
+ torch_dtype=torch.bfloat16,
22
+ device_map="auto" # Use accelerate to manage device placement (CPU/GPU)
23
  )
24
 
25
  # 2. Load the base model's tokenizer
26
  tokenizer = AutoTokenizer.from_pretrained(BASE_MODEL_ID)
27
 
28
+ # 3. Load the LoRA configuration and override the invalid task_type
29
+ peft_config = PeftConfig.from_pretrained(LORA_MODEL_ID)
30
+
31
+ # 💥 CRITICAL FIX: Override the invalid 'text-generation' task type
32
+ # for Causal Language Models (like Llama) to 'CAUSAL_LM'.
33
+ peft_config.task_type = "CAUSAL_LM"
34
+
35
+ # 4. Load the LoRA adapter weights using the corrected config
36
+ model = PeftModel.from_pretrained(base_model, LORA_MODEL_ID, config=peft_config)
37
 
38
+ # 5. Merge the LoRA weights into the base model for faster inference
39
  model = model.merge_and_unload()
40
+
41
+ # Ensure the model is in evaluation mode
42
+ model.eval()
43
+
44
  print("LoRA adapter merged and model ready successfully.")
45
 
46
  except Exception as e:
 
48
  # Re-raise the exception to crash the space if loading fails
49
  raise
50
 
51
+ # --- Prediction/Matching Function ---
52
  def match_cv_jd(cv_text: str, job_description_text: str):
53
  """
54
+ Constructs the chat prompt, tokenizes, runs the LLM, and attempts to extract the JSON output.
55
  """
56
  try:
57
+ # Define the exact prompt structure used for fine-tuning
58
  messages = [
59
  {"role": "system", "content": """
60
  You will receive a CV and a job description. Your task is to output a structured JSON format
 
69
  messages,
70
  add_generation_prompt=True,
71
  return_tensors="pt"
72
+ ).to(model.device)
73
 
74
  # Generate the response
75
  outputs = model.generate(
76
  inputs,
77
  max_new_tokens=512,
78
  do_sample=False,
79
+ pad_token_id=tokenizer.eos_token_id
80
  )
81
 
82
  # Decode the generated text and clean up the prompt
83
+ generated_text = tokenizer.decode(outputs[0], skip_special_tokens=False)
84
+
85
+ # Attempt to clean the output to show only the assistant's response
86
+ # Note: skip_special_tokens=False might show <|end_of_text|>
87
+ assistant_response_start = generated_text.rfind("<|eot_id|>assistant\n")
88
 
 
 
89
  if assistant_response_start != -1:
90
+ # Extract text starting after the assistant's role tag
91
+ raw_json_output = generated_text[assistant_response_start + len("<|eot_id|>assistant\n"):].strip()
92
  else:
93
+ # Fallback to the full generated text if the marker isn't found
94
  raw_json_output = generated_text
95
 
96
+ # Remove any trailing tokens like <|eot_id|> for cleaner output
97
+ raw_json_output = raw_json_output.replace("<|eot_id|>", "").strip()
98
+
99
+ return f"### ✅ Matching Analysis Output (Expected JSON):\n\n```json\n{raw_json_output}\n```"
100
 
101
  except Exception as e:
102
+ return f"### ❌ Prediction Error\n\nAn error occurred during prediction: {e}. This may indicate a hardware memory issue or a timeout."
103
 
104
+ # --- Gradio Interface ---
105
  demo = gr.Interface(
106
  fn=match_cv_jd,
107
  inputs=[
 
110
  ],
111
  outputs="markdown",
112
  title="LlamaFactory CV-Job Matching Demo",
113
+ description=f"Interactive demo for the {LORA_MODEL_ID} model (LoRA on {BASE_MODEL_ID}). This LLM expects a system prompt and outputs structured JSON."
114
  )
115
 
116
  if __name__ == "__main__":