Text Generation
Transformers
PyTorch
TensorFlow
JAX
TensorBoard
Persian
gpt2
text-generation-inference
Run this model with HF Jobs
Run flax-community/gpt2-medium-persian on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.
Paste one of these prompts into your coding agent:
Fine-tune on my dataset
Use HF Jobs and TRL to fine-tune https://huggingface.co/flax-community/gpt2-medium-persian. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.
Run batch inference
Use HF Jobs to run batch inference with https://huggingface.co/flax-community/gpt2-medium-persian on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.
Evaluate on a benchmark
Use HF Jobs to evaluate https://huggingface.co/flax-community/gpt2-medium-persian. Ask me which benchmark to run, then save the scores and the per-example results to a new dataset repo. Run `hf jobs --help` first to learn the CLI.
Quantize for lower memory use
Use HF Jobs to create a 4-bit version of https://huggingface.co/flax-community/gpt2-medium-persian. Push it to a new model repo, then reload it from there and report its memory footprint. Run `hf jobs --help` first to learn the CLI.
Instructions to use flax-community/gpt2-medium-persian with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use flax-community/gpt2-medium-persian with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-generation", model="flax-community/gpt2-medium-persian")# pip install -U transformers accelerate # Load model directly from transformers import AutoTokenizer, AutoModelForCausalLM tokenizer = AutoTokenizer.from_pretrained("flax-community/gpt2-medium-persian") model = AutoModelForCausalLM.from_pretrained("flax-community/gpt2-medium-persian", device_map="auto") - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- vLLM
How to use flax-community/gpt2-medium-persian with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "flax-community/gpt2-medium-persian" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "flax-community/gpt2-medium-persian", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }'Use Docker
docker model run hf.co/flax-community/gpt2-medium-persian
- SGLang
How to use flax-community/gpt2-medium-persian with SGLang:
Install from pip and serve model
# Install SGLang from pip: pip install sglang # Start the SGLang server: python3 -m sglang.launch_server \ --model-path "flax-community/gpt2-medium-persian" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "flax-community/gpt2-medium-persian", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }'Use Docker images
docker run --gpus all \ --shm-size 32g \ -p 30000:30000 \ -v ~/.cache/huggingface:/root/.cache/huggingface \ --env "HF_TOKEN=<secret>" \ --ipc=host \ lmsysorg/sglang:latest \ python3 -m sglang.launch_server \ --model-path "flax-community/gpt2-medium-persian" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "flax-community/gpt2-medium-persian", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }' - Docker Model Runner
How to use flax-community/gpt2-medium-persian with Docker Model Runner:
docker model run hf.co/flax-community/gpt2-medium-persian
Download src/train_tokenizer.py from flax-community/gpt2-medium-persian: direct link, hf CLI and curl.
- Browser
- Download file 5.46 kB
-
https://huggingface.co/flax-community/gpt2-medium-persian/resolve/main/src/train_tokenizer.py
- Command line
-
hf download hf://flax-community/gpt2-medium-persian/src/train_tokenizer.py
-
curl -L -o train_tokenizer.py https://huggingface.co/flax-community/gpt2-medium-persian/resolve/main/src/train_tokenizer.py
5.46 kB
| import ast | |
| import logging | |
| import os | |
| import sys | |
| from dataclasses import dataclass, field | |
| from typing import Dict, List, Optional, Tuple, Union, Any | |
| from datasets import load_dataset | |
| from tokenizers import ByteLevelBPETokenizer | |
| from transformers import ( | |
| HfArgumentParser, | |
| ) | |
| from data_utils import ( | |
| filter_by_lang_regex, | |
| filter_by_num_tokens, | |
| filter_by_num_sents, | |
| filter_by_adv, | |
| normalizer | |
| ) | |
| logger = logging.getLogger(__name__) | |
| class TokenizerArguments: | |
| """ | |
| Arguments to which tokenizer we are going to set up. | |
| """ | |
| output_dir: str = field( | |
| default=".", | |
| metadata={"help": "The output directory where the config will be written."}, | |
| ) | |
| dataset_name: Optional[str] = field( | |
| default=None, metadata={"help": "The name of the dataset to use (via the datasets library)."} | |
| ) | |
| dataset_config_name: Optional[str] = field( | |
| default=None, metadata={"help": "The configuration name of the dataset to use (via the datasets library)."} | |
| ) | |
| train_file: Optional[str] = field(default=None, metadata={"help": "The input training data file (a text file)."}) | |
| cache_dir: Optional[str] = field( | |
| default=None, | |
| metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"}, | |
| ) | |
| special_tokens: Optional[str] = field( | |
| default=None, | |
| metadata={"help": "The list of special tokens that you want to add in your training."} | |
| ) | |
| vocab_size: Optional[int] = field( | |
| default=56000, | |
| metadata={"help": "The size of the final vocabulary, including all tokens and alphabet"} | |
| ) | |
| min_frequency: Optional[int] = field( | |
| default=2, | |
| metadata={"help": "The minimum frequency a pair should have in order to be merged"} | |
| ) | |
| show_progress: Optional[bool] = field( | |
| default=True, | |
| metadata={"help": "Whether to show progress bars while training"} | |
| ) | |
| def __post_init__(self): | |
| if self.special_tokens is None: | |
| special_tokens = [ | |
| "<s>", "<pad>", "</s>", "<unk>", "<mask>", | |
| "<|endoftext|>", "<|startoftext|>", | |
| "<sep>", "<cls>", "<nl>", "<tab>", "<zwnj>" | |
| ] | |
| special_tokens += [f"[U{i}]" for i in range(1, 21)] | |
| else: | |
| special_tokens = list(self.special_tokens.split(",")) | |
| self.special_tokens = special_tokens | |
| if self.dataset_name is None and self.train_file is None: | |
| raise ValueError("Need either a dataset name or a training file.") | |
| else: | |
| if self.train_file is not None: | |
| extension = self.train_file.split(".")[-1] | |
| assert extension in ["csv", "json", "txt"], "`train_file` should be a csv, a json or a txt file." | |
| def main(): | |
| parser = HfArgumentParser([TokenizerArguments]) | |
| if len(sys.argv) == 2 and sys.argv[1].endswith(".json"): | |
| # If we pass only one argument to the script and it's the path to a json file, | |
| # let's parse it to get our arguments. | |
| tokenizer_args = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]))[0] | |
| else: | |
| tokenizer_args = parser.parse_args_into_dataclasses()[0] | |
| # Setup logging | |
| logging.basicConfig( | |
| format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", | |
| datefmt="%m/%d/%Y %H:%M:%S", | |
| handlers=[logging.StreamHandler(sys.stdout)], | |
| ) | |
| logger.setLevel(logging.INFO) | |
| logger.info(f"Training tokenizer") | |
| if tokenizer_args.dataset_name is not None: | |
| raw_dataset = load_dataset( | |
| tokenizer_args.dataset_name, | |
| tokenizer_args.dataset_config_name, | |
| cache_dir=tokenizer_args.cache_dir, | |
| split="train" | |
| ) | |
| else: | |
| data_files = {"train": tokenizer_args.train_file} | |
| extension = tokenizer_args.train_file.split(".")[-1] | |
| if extension == "txt": | |
| extension = "text" | |
| raw_dataset = load_dataset( | |
| extension, | |
| data_files=data_files, | |
| delimiter="\t", | |
| cache_dir=tokenizer_args.cache_dir, | |
| ) | |
| logger.info("Preprocessing the dataset") | |
| dataset = raw_dataset.filter(lambda example: filter_by_lang_regex(example["text"], ratio=0.75)) | |
| dataset = dataset.filter(lambda example: filter_by_num_tokens(example["text"], gt=64)) | |
| dataset = dataset.filter(lambda example: filter_by_num_sents(example["text"], gt=2)) | |
| dataset = dataset.filter(lambda example: filter_by_adv(example["text"], ratio=50)) | |
| dataset = dataset.map(normalizer) | |
| logger.info(f"Preprocessed dataset kept {len(dataset)} out of {len(raw_dataset)}") | |
| tokenizer = ByteLevelBPETokenizer() | |
| def batch_iterative(batch_size=1000): | |
| for i in range(0, len(dataset), batch_size): | |
| yield dataset[i: i + batch_size]["text"] | |
| tokenizer.train_from_iterator( | |
| batch_iterative(), | |
| vocab_size=tokenizer_args.vocab_size, | |
| special_tokens=tokenizer_args.special_tokens, | |
| min_frequency=tokenizer_args.min_frequency, | |
| show_progress=tokenizer_args.show_progress, | |
| ) | |
| logger.info(f"Your tokenizer saved here {tokenizer_args.output_dir}") | |
| os.makedirs(tokenizer_args.output_dir, exist_ok=True) | |
| tokenizer.save_model(tokenizer_args.output_dir) | |
| tokenizer.save(f"{tokenizer_args.output_dir}/tokenizer.json", pretty=True) | |
| if __name__ == '__main__': | |
| main() | |