Spaces:
Configuration error
Configuration error
Upload Streamlit app and model files for Space deployment (filtered)
Browse filesFiles changed (12)
- README.md+41-19
- added_tokens.jsonAdded+6
- app.pyAdded+96
- config.jsonAdded+40
- generation_config.jsonAdded+10
- merges.txtAdded
- model.safetensorsAdded+3
- requirements.txt+6-3
- special_tokens_map.jsonAdded+30
- tokenizer.jsonAdded
- training_args.binAdded+3
- vocab.jsonAdded
12345678910111213141516171819---title: Boxcode Appemoji: 🚀colorFrom: redcolorTo: redsdk: dockerapp_port: 8501tags:- streamlitpinned: falseshort_description: interface for my model---# Welcome to Streamlit!Edit `/src/streamlit_app.py` to customize this app to your heart's desire. :heart:If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [communityforums](https://discuss.streamlit.io).1234567891011121314151617181920212223242526272829303132333435363738394041# Fine-tuned Code Model for Vite, React, Next.js, Node.js, Python, and GoThis model is a fine-tuned version of [microsoft/CodeGPT-small-java-adaptedgpt2](https://huggingface.co/microsoft/CodeGPT-small-java-adaptedgpt2)adapted for code understanding and generation tasks across several technologies:Vite, React, Next.js, Node.js, Python, and Go.The model was fine-tuned on code data extracted from private GitHub repositories.## How to useYou can load and use this model with the `transformers` library:```pythonfrom transformers import AutoModelForCausalLM, AutoTokenizermodel_path = "." # Or the repository ID after pushing to Hugging Face Hubtokenizer = AutoTokenizer.from_pretrained(model_path)model = AutoModelForCausalLM.from_pretrained(model_path)# Example inferenceinput_text = "def fibonacci("input_ids = tokenizer(input_text, return_tensors="pt").input_idsoutput_ids = model.generate(input_ids, max_length=50)output_text = tokenizer.decode(output_ids[0], skip_special_tokens=True)print(output_text)```## Fine-tuning Details- **Base Model:** microsoft/CodeGPT-small-java-adaptedgpt2- **Fine-tuning Data:** Code from private GitHub repositories focusing on Vite, React, Next.js, Node.js, Python, and Go.- **Training Parameters:** (Include key parameters from TrainingArguments here, e.g., epochs, batch size)- Number of Epochs: 3- Per Device Train Batch Size: 2- Learning Rate: 2e-5## Limitations- This model was fine-tuned on a limited private dataset and may not generalize well to all code scenarios or languages.- The model size is optimized for deployment on Hugging Face Spaces with a 2GB limit, which might impact its performance compared to larger models.
123456{ "</s>": 50258, "<pad>": 50257, "<s>": 50259, "<|UNKNOWN|>": 50260}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
import streamlit as stfrom transformers import AutoModelForCausalLM, AutoTokenizerimport torch
# Define the path to the model (it's in the root of the Space)model_path = "."# Define the repository ID for display purposesrepo_id_display = "arnoxide/boxcode-model" # Display the model repo, not the app repo
# Load the model and tokenizer (cache them using Streamlit's caching)@st.cache_resource # Use st.cache_resource for models and other resourcesdef load_model(): """Loads the fine-tuned model and tokenizer.""" try: tokenizer = AutoTokenizer.from_pretrained(model_path) model = AutoModelForCausalLM.from_pretrained(model_path) # Ensure model is on GPU if available if torch.cuda.is_available(): model.to('cuda') return tokenizer, model except Exception as e: st.error(f"Error loading model or tokenizer: {e}") return None, None
tokenizer, model = load_model()
def generate_code(prompt, tokenizer, model, max_length=200): """Generates code based on a given prompt using the loaded model.""" if tokenizer is None or model is None: return "Error: Model or tokenizer not loaded."
try: input_ids = tokenizer(prompt, return_tensors="pt").input_ids
# Ensure input_ids are on the same device as the model if torch.cuda.is_available(): input_ids = input_ids.to('cuda')
# Generate text # Use appropriate generation parameters (e.g., do_sample=True, top_k, top_p) # for more varied output if needed. Keep it simple for now. output_ids = model.generate( input_ids, max_length=max_length, num_return_sequences=1, no_repeat_ngram_size=2, pad_token_id=tokenizer.pad_token_id # Ensure pad token is handled )
# Decode the output # Decode the entire output sequence, including the prompt generated_text_with_prompt = tokenizer.decode(output_ids[0], skip_special_tokens=True)
# Optionally, extract only the generated part (after the prompt) # This is a simple approach, may need refinement based on model behavior if generated_text_with_prompt.startswith(prompt): generated_text = generated_text_with_prompt[len(prompt):].strip() else: generated_text = generated_text_with_prompt # Fallback if prompt is not at start
return generated_text
except Exception as e: return f"Error during code generation: {e}"
# Streamlit Application Layoutst.title("Code Generation Model")st.write(f"Powered by a fine-tuned model hosted on Hugging Face Hub ({repo_id_display})")
# Input areaprompt_text = st.text_area("Enter your code prompt here:", height=150, key="prompt_input")
# Generation buttonif st.button("Generate Code"): if prompt_text: with st.spinner("Generating code..."): # Call the code generation function generated_code = generate_code(prompt_text, tokenizer, model) # Store the generated code in session state to persist it st.session_state['generated_code'] = generated_code else: st.warning("Please enter a prompt.")
# Output area# Use st.session_state to retrieve and display the generated code after a rerunif 'generated_code' in st.session_state and st.session_state['generated_code']: st.text_area("Generated Code:", value=st.session_state['generated_code'], height=300, key="generated_output") # Alternatively, for code highlighting: # st.code(st.session_state['generated_code'], language='python') # Specify language if known
st.write("---")st.write("This is a simple Streamlit application for demonstrating code generation.")
12345678910111213141516171819202122232425262728293031323334353637383940{ "activation_function": "gelu_new", "architectures": [ "GPT2LMHeadModel" ], "attn_pdrop": 0.1, "bos_token_id": 50259, "dtype": "float32", "embd_pdrop": 0.1, "eos_token_id": 50258, "gradient_checkpointing": false, "initializer_range": 0.02, "layer_norm_epsilon": 1e-05, "model_type": "gpt2", "n_ctx": 1024, "n_embd": 768, "n_head": 12, "n_inner": null, "n_layer": 12, "n_positions": 1024, "pad_token_id": 50257, "reorder_and_upcast_attn": false, "resid_pdrop": 0.1, "scale_attn_by_inverse_layer_idx": false, "scale_attn_weights": true, "summary_activation": null, "summary_first_dropout": 0.1, "summary_proj_to_labels": true, "summary_type": "cls_index", "summary_use_proj": true, "task_specific_params": { "text-generation": { "do_sample": true, "max_length": 50 } }, "transformers_version": "4.56.1", "use_cache": true, "vocab_size": 50261}12345678910{ "_from_model_config": true, "bos_token_id": 50259, "eos_token_id": [ 50258, 50256 ], "pad_token_id": 50257, "transformers_version": "4.56.1"}123version https://git-lfs.github.com/spec/v1oid sha256:e03d69f49f3a625693ee56c05915faa4215d4ad5f308502da7b46be957ae3ae1size 497786496123altairpandasstreamlit123456streamlittransformerstorchdatasets # Needed if your app uses the datasets library directly, otherwise optional# Add other dependencies if your app needs them (e.g., specific torch version, specific datasets version)
123456789101112131415161718192021222324252627282930{ "bos_token": { "content": "<s>", "lstrip": false, "normalized": true, "rstrip": false, "single_word": false }, "eos_token": { "content": "</s>", "lstrip": false, "normalized": true, "rstrip": false, "single_word": false }, "pad_token": { "content": "<pad>", "lstrip": false, "normalized": true, "rstrip": false, "single_word": false }, "unk_token": { "content": "<|UNKNOWN|>", "lstrip": false, "normalized": true, "rstrip": false, "single_word": false }}123version https://git-lfs.github.com/spec/v1oid sha256:2cfe1a2b998b5590e8b9424c6c30b1de2c5d353245465cf078ec428894df9d96size 5713README.md+41-19
added_tokens.jsonAdded+6
app.pyAdded+96
config.jsonAdded+40
generation_config.jsonAdded+10
merges.txtAdded
model.safetensorsAdded+3
requirements.txt+6-3
special_tokens_map.jsonAdded+30
tokenizer.jsonAdded
training_args.binAdded+3
vocab.jsonAdded