Views
No views yet
# Main Markdown content
markdown_content = f"""{base_model_id} model, fine-tuned for enhanced AI safety as part of the SafeSky AI initiative by {attribution}.checkpoint-100 of the fine-tuning process.Anthropic/hh-rlhf (Helpful and Harmless Reinforcement Learning from Human Feedback) dataset. This dataset contains human preferences over model responses, focusing on helpfulness and harmlessness.{base_model_id}) and then apply the adapters from this repository ({repo_id}).1import torch
2from transformers import AutoTokenizer, AutoModelForCausalLM
3from peft import PeftModel
4
5# Base model ID
6base_model_id = "{base_model_id}"
7# Your adapter repository ID
8adapter_repo_id = "{repo_id}"
9
10# --- Load Base Model and Tokenizer ---
11print(f"Loading base model: {{base_model_id}}")
12# Load the base model (choose quantization or full precision based on your hardware)
13# Example using bfloat16 (requires capable GPU)
14base_model = AutoModelForCausalLM.from_pretrained(
15 base_model_id,
16 torch_dtype=torch.bfloat16, # Or torch.float16 or use BitsAndBytesConfig for 4-bit
17 device_map="auto"
18)
19
20print(f"Loading tokenizer: {{base_model_id}}")
21# It's usually sufficient to use the base model's tokenizer
22tokenizer = AutoTokenizer.from_pretrained(base_model_id)
23
24# --- Load LoRA Adapters ---
25print(f"Loading LoRA adapter: {{adapter_repo_id}}")
26# Load the PeftModel by merging the adapter from your repo onto the base model
27model = PeftModel.from_pretrained(base_model, adapter_repo_id)
28print("LoRA adapter loaded and applied successfully!")
29
30# --- Optional: Merge for faster inference (requires more memory) ---
31# print("Attempting to merge model...")
32# model = model.merge_and_unload()
33# print("Model merged.")
34
35# --- Inference Example ---
36prompt = "Human: Please explain the concept of AI safety. Assistant:"
37# Format the input using the chat template appropriate for Gemma
38inputs = tokenizer(f"<start_of_turn>user\\n{{prompt}}<end_of_turn>\\n<start_of_turn>model\\n", return_tensors="pt").to(model.device)
39
40print("Generating response...")
41with torch.no_grad():
42 outputs = model.generate(**inputs, max_new_tokens=150, do_sample=True, temperature=0.7, pad_token_id=tokenizer.eos_token_id) # Ensure pad_token_id is set
43
44print("\\nResponse:")
45# Decode skipping special tokens, but be mindful that the stop sequence might be part of the output
46# Depending on the fine-tuning data, you might need more sophisticated stopping logic
47print(tokenizer.decode(outputs[0], skip_special_tokens=True))
48Intended Use
49This model adapter is intended for research purposes in AI safety, for developing safer conversational AI prototypes, and for educational purposes related to fine-tuning and model alignment.
50
51Limitations and Bias
52Safety is Not Guaranteed: While fine-tuned for safety, this model may still generate unsafe, biased, or otherwise problematic content. It should not be deployed in critical applications without rigorous testing and safety guardrails.
53
54Inherited Bias: The model inherits biases present in the base {base_model_id} model and the Anthropic/hh-rlhf dataset.
55
56Performance: Fine-tuning might affect the model's performance on tasks unrelated to safety. The focus was on improving harmlessness based on the HH-RLHF data.
57
58License
59The use of this adapter is subject to the terms of the original Gemma model license. Please refer to the Gemma Terms of Use provided by Google. This adapter itself does not impose additional license restrictions beyond those of the base model and the training data.
60"""
61return yaml_header.strip() + "\n\n" + markdown_content.strip()
62
63--- Main Script Logic ---
64if name == "main":
65print(f"--- Preparing to update README.md for repo: {REPO_ID} ---")
66# --- 1. Authenticate ---
67token = HfFolder.get_token() # Try to get token saved by 'huggingface-cli login'
68if token is None:
69 print("Hugging Face token not found locally.")
70 # Fallback to asking for token (less secure for scripts)
71 # token = getpass("Please enter your Hugging Face Access Token (with write permission): ")
72 # Alternatively, instruct user to run 'huggingface-cli login' first
73 print("Please run 'huggingface-cli login' in your terminal first.")
74 exit(1) # Exit if no token available
75
76try:
77 api = HfApi(token=token)
78 user = api.whoami()
79 print(f"Authenticated as: {user['name']}")
80 if user['name'] != REPO_ID.split('/')[0]:
81 print(f"Warning: Logged in user ({user['name']}) does not match repo owner ({REPO_ID.split('/')[0]}). Make sure you have write access.")
82except Exception as e:
83 print(f"Authentication failed: {e}")
84 exit(1)
85
86# --- 2. Generate README Content ---
87print("Generating README.md content...")
88readme_content = generate_readme_content(REPO_ID, BASE_MODEL_ID, ATTRIBUTION)
89# print("\nGenerated Content Preview:\n", readme_content[:500], "...") # Optional preview
90
91# --- 3. Upload README.md ---
92print(f"Uploading generated README.md to {REPO_ID}...")
93try:
94 # Upload the content as a file-like object in memory
95 from io import BytesIO
96 readme_bytes = readme_content.encode('utf-8')
97 api.upload_file(
98 path_or_fileobj=BytesIO(readme_bytes),
99 path_in_repo="README.md", # Target path in the repository
100 repo_id=REPO_ID,
101 repo_type="model",
102 commit_message="Update model card with detailed info and usage example"
103 )
104 print("README.md uploaded successfully!")
105 print(f"Visit your repository at: https://huggingface.co/{REPO_ID}")
106except Exception as e:
107 print(f"Failed to upload README.md: {e}")
108 import traceback
109 traceback.print_exc()
110 print("\nUpload failed.")