File size: 6,469 Bytes
3430cbb
 
6b463ef
3430cbb
6b463ef
 
3430cbb
 
6b463ef
 
 
 
 
 
3430cbb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6b463ef
babde94
6b463ef
50220da
6b463ef
 
3310e88
f6aa47a
6b463ef
 
 
 
 
 
 
f6aa47a
6b463ef
 
f6aa47a
6b463ef
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3430cbb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
from langchain_community.vectorstores import Chroma
from langchain_community.embeddings import HuggingFaceBgeEmbeddings

from langchain.docstore.document import Document
from transformers import AutoModelForCausalLM, AutoTokenizer, GenerationConfig
from peft import PeftModel
from config import *
import os
import torch

if torch.cuda.is_available():
    device = "cuda"
else:
    device = "cpu"

os.environ['CURL_CA_BUNDLE'] = ""
embedding_int = HuggingFaceBgeEmbeddings(
    model_name=MODEL_NAME,
    encode_kwargs=ENCODE_KWARGS,
    query_instruction=QUERY_INSTRUCTION
)

embedding_sim = HuggingFaceBgeEmbeddings(
    model_name=MODEL_NAME,
    encode_kwargs=ENCODE_KWARGS,
    query_instruction='Retrieve semantically similar text.'
)

db = Chroma(persist_directory=PERSIST_DIRECTORY, embedding_function=embedding_int)
retriever = db.as_retriever(search_kwargs={"k": TOP_K})


LLM_MODEL = "meta-llama/Meta-Llama-3-8B-Instruct"
lora_weights = "wt3639/Llama-3-8B-Instruct_CourseRec_lora"

hf_auth  = os.environ.get("hf_token")


tokenizer = AutoTokenizer.from_pretrained(LLM_MODEL, token=hf_auth)


first_token = 'First'
second_token = 'Second'
# 获取token的ID
first_id = tokenizer.convert_tokens_to_ids(first_token)
second_id = tokenizer.convert_tokens_to_ids(second_token)
model = AutoModelForCausalLM.from_pretrained(
            LLM_MODEL,
            torch_dtype=torch.float16,
            device_map="auto",
            token=hf_auth,
        )

rec_adapter = PeftModel.from_pretrained(
            model,
            lora_weights,
            torch_dtype=torch.float16,
            device_map={'': 0}
        )
      
tokenizer.padding_side = "left"
    # unwind broken decapoda-research config
#model.half()  # seems to fix bugs for some users.
rec_adapter.eval()

rec_adapter.config.pad_token_id = tokenizer.pad_token_id = 0  # unk
rec_adapter.config.bos_token_id = 1
rec_adapter.config.eos_token_id = 2

def generate_prompt(target_occupation, skill_gap, courses):
    return f"""
### Instruction:
"As an education expert, you have been provided with a target occupation, a skill gap, and information on two candidate courses. Your task is to determine which course better matches the target occupation and skill gap. Please respond with 'First' or 'Second' to indicate your recommendation.

### Input:
Target Occupation: {target_occupation}
Skill Gap: {skill_gap}
candidate courses: {courses}

### Response:
"""
'''
prompt_re = ChatPromptTemplate.from_template(template_re)
chain_re = (
    runnable
    | prompt_re
)
'''
def evaluate(
        prompt=None,
        temperature=0,
        top_p=1.0,
        top_k=40,
        num_beams=1,
        max_new_tokens=120,
        batch_size=1,
        **kwargs,
    ):

        inputs = tokenizer(prompt, return_tensors="pt", padding=True, truncation=True).to(device)
        generation_config = GenerationConfig(
            temperature=temperature,
            top_p=top_p,
            top_k=top_k,
            num_beams=num_beams,
            **kwargs,
        )
        with torch.no_grad():
            generation_output = model.generate(
                **inputs,
                generation_config=generation_config,
                return_dict_in_generate=True,
                output_scores=True,
                max_new_tokens=max_new_tokens,
                # batch_size=batch_size,
                eos_token_id=tokenizer.eos_token_id,
                pad_token_id=tokenizer.eos_token_id,
            )
        scores = generation_output.scores[0].softmax(dim=-1)
        logits = torch.tensor(scores[:,[first_id, second_id]], dtype=torch.float32).softmax(dim=-1)
        s = generation_output.sequences
        output = tokenizer.batch_decode(s, skip_special_tokens=True)
        output = [_.split('Response:\n')[-1] for _ in output]
        return output, logits.tolist()

def compare_docs_with_context(doc_a, doc_b, df_course, target_occupation_name, target_occupation_dsp,skill_gap):
    # Extract course details from the data frame
    course_a = df_course[df_course['course_id'] == int(doc_a.metadata['id'])].iloc[0]
    course_b = df_course[df_course['course_id'] == int(doc_b.metadata['id'])].iloc[0]
    print('comapring...')
    print(course_a['course_name'], course_b['course_name'])
    # Prepare the input for chain_re.invoke
    
    courses = f"First: name: {course_a['course_name']}  description:{course_a['course_content_limited']} Second: name: {course_b['course_name']}  description:{course_b['course_content_limited']}" 
    #courses = f"First: name: {course_a['course_name']}  skills:{course_a['course_skills_edu']} Second: name: {course_b['course_name']}  skills:{course_b['course_skills_edu']}" 
    target_occupation = f"name: {target_occupation_name} description: {target_occupation_dsp}"
    skill_gap = skill_gap
    prompt = generate_prompt(target_occupation, skill_gap, courses)
    prompt = [prompt]
    output, logit = evaluate(prompt)
    # Compare based on the response: [A] means doc_a > doc_b, [B] means doc_a < doc_b
    print(output, logit)
    if logit[0][0] > logit[0][1]:
        return 1  # doc_a should come before doc_b
    elif logit[0][0] < logit[0][1]:
        return -1  # doc_a should come after doc_b
    else:
        return 0  # Consider them equal if the response is unclear

def find_similar_occupation(target_occupation_query, berufe, top_k, similarity_func):
  
    # Pro kurs wird ein Document erstellt. Dieses enthält Metadaten sowie einen page_content. 
    # Der Inhalt von page_content wird embedded und so für die sucher verwendet.
    docs = []
    for index, beruf in berufe.iterrows():  
        # Create document.
        doc = Document(
            page_content= beruf['short name'] + ' ' + beruf['full name'] + ' ' + beruf['description'],  
            metadata={
                "id": beruf["id"],
                "name": beruf['short name'],
                "description": beruf["description"],
                "entry_requirements": beruf["entry requirements"]
            },
        )
        docs.append(doc)
    
    db_temp = Chroma.from_documents(documents = docs, embedding= embedding_sim, collection_metadata = {"hnsw:space": similarity_func})
    # Retriever will search for the top_5 most similar documents to the query.
    retriever_temp = db_temp.as_retriever(search_kwargs={"k": top_k})
    top_similar_occupations = retriever_temp.get_relevant_documents(target_occupation_query)

    return top_similar_occupations