Views
No views yet
1import torch
2import transformers
3
4if torch.cuda.is_available():
5 torch.set_default_device("cuda")
6else:
7 torch.set_default_device("cpu")
8
9model = transformers.AutoModelForCausalLM.from_pretrained("microsoft/Orca-2-7b", device_map='auto')
10
11# https://github.com/huggingface/transformers/issues/27132
12# please use the slow tokenizer since fast and slow tokenizer produces different tokens
13tokenizer = transformers.AutoTokenizer.from_pretrained(
14 "microsoft/Orca-2-7b",
15 use_fast=False,
16 )
17
18system_message = "You are Orca, an AI language model created by Microsoft. You are a cautious assistant. You carefully follow instructions. You are helpful and harmless and you follow ethical guidelines and promote positive behavior."
19user_message = "How can you determine if a restaurant is popular among locals or mainly attracts tourists, and why might this information be useful?"
20
21prompt = f"<|im_start|>system\n{system_message}<|im_end|>\n<|im_start|>user\n{user_message}<|im_end|>\n<|im_start|>assistant"
22
23inputs = tokenizer(prompt, return_tensors='pt')
24output_ids = model.generate(inputs["input_ids"],)
25answer = tokenizer.batch_decode(output_ids)[0]
26
27print(answer)
28
29# This example continues showing how to add a second turn message by the user to the conversation
30second_turn_user_message = "Give me a list of the key points of your first answer."
31
32# we set add_special_tokens=False because we dont want to automatically add a bos_token between messages
33second_turn_message_in_markup = f"\n<|im_start|>user\n{second_turn_user_message}<|im_end|>\n<|im_start|>assistant"
34second_turn_tokens = tokenizer(second_turn_message_in_markup, return_tensors='pt', add_special_tokens=False)
35second_turn_input = torch.cat([output_ids, second_turn_tokens['input_ids']], dim=1)
36
37output_ids_2 = model.generate(second_turn_input,)
38second_turn_answer = tokenizer.batch_decode(output_ids_2)[0]
39
40print(second_turn_answer)1import os
2import math
3import transformers
4import torch
5
6from azure.ai.contentsafety import ContentSafetyClient
7from azure.core.credentials import AzureKeyCredential
8from azure.core.exceptions import HttpResponseError
9from azure.ai.contentsafety.models import AnalyzeTextOptions
10
11CONTENT_SAFETY_KEY = os.environ["CONTENT_SAFETY_KEY"]
12CONTENT_SAFETY_ENDPOINT = os.environ["CONTENT_SAFETY_ENDPOINT"]
13
14# We use Azure AI Content Safety to filter out any content that reaches "Medium" threshold
15# For more information: https://learn.microsoft.com/en-us/azure/ai-services/content-safety/
16def should_filter_out(input_text, threshold=4):
17 # Create an Content Safety client
18 client = ContentSafetyClient(CONTENT_SAFETY_ENDPOINT, AzureKeyCredential(CONTENT_SAFETY_KEY))
19
20 # Construct a request
21 request = AnalyzeTextOptions(text=input_text)
22
23 # Analyze text
24 try:
25 response = client.analyze_text(request)
26 except HttpResponseError as e:
27 print("Analyze text failed.")
28 if e.error:
29 print(f"Error code: {e.error.code}")
30 print(f"Error message: {e.error.message}")
31 raise
32 print(e)
33 raise
34
35 categories = ["hate_result", "self_harm_result", "sexual_result", "violence_result"]
36 max_score = -math.inf
37 for category in categories:
38 max_score = max(max_score, getattr(response, category).severity)
39
40 return max_score >= threshold
41
42model_path = 'microsoft/Orca-2-7b'
43device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
44model = transformers.AutoModelForCausalLM.from_pretrained(model_path)
45model.to(device)
46
47tokenizer = transformers.AutoTokenizer.from_pretrained(
48 model_path,
49 model_max_length=4096,
50 padding_side="right",
51 use_fast=False,
52 add_special_tokens=False,
53)
54
55system_message = "You are Orca, an AI language model created by Microsoft. You are a cautious assistant. You carefully follow instructions. You are helpful and harmless and you follow ethical guidelines and promote positive behavior."
56user_message = "\" \n :You can't just say, \"\"that's crap\"\" and remove it without gaining a consensus. You already know this, based on your block history. —/ \" \nIs the comment obscene? \nOptions : Yes, No."
57
58prompt = f"<|im_start|>system\n{system_message}<|im_end|>\n<|im_start|>user\n{user_message}<|im_end|>\n<|im_start|>assistant"
59
60inputs = tokenizer(prompt, return_tensors='pt')
61inputs = inputs.to(device)
62
63output_ids = model.generate(inputs["input_ids"], max_length=4096, do_sample=False, temperature=0.0, use_cache=True)
64sequence_length = inputs["input_ids"].shape[1]
65new_output_ids = output_ids[:, sequence_length:]
66answers = tokenizer.batch_decode(new_output_ids, skip_special_tokens=True)
67final_output = answers[0] if not should_filter_out(answers[0]) else "[Content Filtered]"
68
69print(final_output)1@misc{mitra2023orca,
2 title={Orca 2: Teaching Small Language Models How to Reason},
3 author={Arindam Mitra and Luciano Del Corro and Shweti Mahajan and Andres Codas and Clarisse Simoes and Sahaj Agrawal and Xuxi Chen and Anastasia Razdaibiedina and Erik Jones and Kriti Aggarwal and Hamid Palangi and Guoqing Zheng and Corby Rosset and Hamed Khanpour and Ahmed Awadallah},
4 year={2023},
5 eprint={2311.11045},
6 archivePrefix={arXiv},
7 primaryClass={cs.AI}
8}