├── figures └── teaser.png ├── requirements-dev.txt ├── SemiKong_OSAI4MU_AAAI_25.pdf ├── requirements.txt ├── .pre-commit-config.yaml ├── inference_llm_openai.py ├── configs ├── inference-config.yaml └── training-config.yaml ├── INSTALL.md ├── inference_vllm_server.py ├── logging_setup.py ├── .gitignore ├── raw_inference.py ├── training.py ├── LICENSE └── README.md /figures/teaser.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aitomatic/semikong/HEAD/figures/teaser.png -------------------------------------------------------------------------------- /requirements-dev.txt: -------------------------------------------------------------------------------- 1 | -r requirements.txt 2 | black 3 | isort 4 | pre-commit 5 | pylint 6 | tqdm -------------------------------------------------------------------------------- /SemiKong_OSAI4MU_AAAI_25.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aitomatic/semikong/HEAD/SemiKong_OSAI4MU_AAAI_25.pdf -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | --find-links https://download.pytorch.org/whl/torch_stable.html 2 | accelerate 3 | async-lru 4 | aiohttp 5 | bitsandbytes 6 | datasets 7 | fastapi 8 | fastapi-cli 9 | fire 10 | flash_attn 11 | gradio 12 | gradio_client 13 | huggingface-hub 14 | langchain 15 | langchain-community 16 | langchain-core 17 | openai 18 | optimum 19 | packaging 20 | pydantic 21 | pydantic_core 22 | torch==2.3.0+cu121 23 | torchaudio==2.3.1+cu121 24 | torchvision==0.18.1+cu121 25 | transformers 26 | uvicorn 27 | vllm 28 | vllm-flash-attn -------------------------------------------------------------------------------- /.pre-commit-config.yaml: -------------------------------------------------------------------------------- 1 | exclude: ^venv/.*| 2 | repos: 3 | - repo: https://github.com/pre-commit/pre-commit-hooks 4 | rev: v4.4.0 5 | hooks: 6 | - id: check-ast 7 | - id: check-merge-conflict 8 | - id: check-yaml 9 | - id: end-of-file-fixer 10 | - id: fix-encoding-pragma 11 | - id: requirements-txt-fixer 12 | - id: trailing-whitespace 13 | - repo: https://github.com/myint/autoflake 14 | rev: v2.2.1 15 | hooks: 16 | - id: autoflake 17 | args: 18 | - --in-place 19 | - --expand-star-imports 20 | - repo: https://github.com/dosisod/refurb 21 | rev: 68a878e 22 | hooks: 23 | - id: refurb 24 | - repo: https://github.com/psf/black 25 | rev: 23.9.1 26 | hooks: 27 | - id: black -------------------------------------------------------------------------------- /inference_llm_openai.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | import os 3 | 4 | import openai 5 | 6 | parser = argparse.ArgumentParser(description="Inference for LLM OpenAI") 7 | parser.add_argument('--api_key', type=str, help='Input your OpenAI API key') 8 | args = parser.parse_args() 9 | api_key = args.api_key 10 | 11 | api_key = os.getenv("OPENAI_API_KEY") if api_key is None else api_key 12 | client = openai.OpenAI(api_key=api_key) 13 | 14 | 15 | def get_answer(prompt, model="gpt-4o", system_message="You are a helpful assistant."): 16 | response = client.chat.completions.create( 17 | model=model, 18 | messages=[ 19 | {"role": "system", "content": system_message}, 20 | {"role": "user", "content": prompt} 21 | ] 22 | ) 23 | return response.choices[0].message.content 24 | 25 | 26 | if __name__ == "__main__": 27 | prompt = "What is the capital of France?" 28 | print(get_answer(prompt)) 29 | -------------------------------------------------------------------------------- /configs/inference-config.yaml: -------------------------------------------------------------------------------- 1 | model: 2 | model_name: "model_path_folder or model_name_hf" 3 | new_model: "semikong-8b" 4 | dataset_name: "dataset_path_folder or dataset_name_hf" 5 | use_4bit: True 6 | use_nested_quant: False 7 | bnb_4bit_compute_dtype: "float16" 8 | bnb_4bit_quant_type: "nf4" 9 | max_seq_length: None 10 | output_dir: "./results" 11 | device_map: {"": 0} 12 | 13 | training: 14 | num_train_epochs: 2 15 | per_device_train_batch_size: 4 16 | per_device_eval_batch_size: 4 17 | gradient_accumulation_steps: 1 18 | learning_rate: 2e-4 19 | max_grad_norm: 0.3 20 | weight_decay: 0.001 21 | fp16: False 22 | bf16: False 23 | packing: False 24 | gradient_checkpointing: True 25 | optim: "paged_adamw_32bit" 26 | lr_scheduler_type: "cosine" 27 | max_steps: -1 28 | warmup_ratio: 0.03 29 | group_by_length: True 30 | save_steps: 10 31 | logging_steps: 1 32 | 33 | lora: 34 | lora_alpha: 16 35 | lora_dropout: 0.1 36 | lora_r: 64 37 | -------------------------------------------------------------------------------- /configs/training-config.yaml: -------------------------------------------------------------------------------- 1 | model: 2 | model_name: "model_path_folder_or_model_name_hf" 3 | new_model: "semikong-8b" 4 | use_4bit: True 5 | use_nested_quant: False 6 | bnb_4bit_compute_dtype: "float16" 7 | bnb_4bit_quant_type: "nf4" 8 | device_map: {"": 0} 9 | output_dir: "./results" 10 | dataset_name: "dataset_path_folder_or_dataset_name_hf" 11 | 12 | training: 13 | num_train_epochs: 2 14 | per_device_train_batch_size: 4 15 | per_device_eval_batch_size: 4 16 | gradient_accumulation_steps: 1 17 | learning_rate: 2e-4 18 | max_grad_norm: 0.3 19 | weight_decay: 0.001 20 | max_seq_length: None 21 | fp16: False 22 | bf16: False 23 | packing: False 24 | gradient_checkpointing: True 25 | optim: "paged_adamw_32bit" 26 | lr_scheduler_type: "cosine" 27 | max_steps: -1 28 | warmup_ratio: 0.03 29 | group_by_length: True 30 | save_steps: 10 31 | logging_steps: 1 32 | 33 | lora: 34 | lora_alpha: 16 35 | lora_dropout: 0.1 36 | lora_r: 64 37 | -------------------------------------------------------------------------------- /INSTALL.md: -------------------------------------------------------------------------------- 1 | # Setup SEMIKONG 2 | 3 | This documentation dedicated to instruct on how to setup the environment for training, evaluation and inference SEMIKONG model. 4 | 5 | ## Requirement Hardware 6 | - CUDA Version: >= 10.x (ideally 11.x) 7 | ~~~ 8 | 1. SEMIKONG 8B Chat 9 | - CPU: Expected to be around 4 cores 10 | - GPU: Any NVIDIA GPU model with at least 16GB VRAM (A100, A30, RTX 3090, etc.) 11 | - Disk Memory: At least 10GB disk space 12 | - RAM Memory: At least 16GB 13 | 14 | 2. SEMIKONG 70B Chat 15 | - CPU: Expected to be around 8 cores 16 | - GPU: Any NVIDIA GPU model with at least 150GB VRAM. Recommend high-end GPU such as A100 or H100 or > RTX 3000 17 | - Disk Memory: At least 20GB disk space 18 | - RAM Memory: At least 64GB 19 | ~~~ 20 | 21 | ## Environment Setup 22 | 23 | - Using `conda` or `poetry` or `venv` to setup the virtual environment 24 | ~~~ 25 | conda create --name semikong-env python=3.11 26 | conda activate semikong-env 27 | pip install -r requirements.txt 28 | ~~~ 29 | 30 | ## Training 31 | ~~~ 32 | 1. Download the Meta-LLaMA/Meta-LLaMA base model first on HuggingFace Hub 33 | 2. Download the dataset for training semiconductor manufacturing process (should follow the alpaca style) 34 | 3. Create a foler `model` which contains the base model 35 | 4. Create a folder `data` which contains the dataset 36 | 5. Replace the path to the model and dataset foldr in `training.py` and `raw_inference.py` 37 | 6. Run `python training.py` 38 | 7. Run `raw_inference.py` 39 | ~~~ 40 | 41 | ## Inference 42 | ~~~ 43 | 1. Using OpenAI Client: 44 | python -m vllm.entrypoints.openai.api_server --model --dtype auto --max-lora-rank 32 --api-key token-abc123 45 | 46 | 2. Using vLLM Server: 47 | python -m vllm.entrypoints.api_server --model --device cuda --max-lora-rank 32 --dtype auto --port 8080 48 | ~~~ -------------------------------------------------------------------------------- /inference_vllm_server.py: -------------------------------------------------------------------------------- 1 | # For further development, please refer to this documentation from vLLM: https://docs.vllm.ai/en/stable/getting_started/examples/api_client.html 2 | 3 | import json 4 | import logging 5 | import os 6 | import time 7 | from typing import Iterable, List 8 | 9 | import requests 10 | 11 | BASE_URL = os.environ["PATH"] 12 | 13 | HEADERS = {"Content-Type": "application/json", "User-Agent": "Test Client"} 14 | 15 | 16 | def post_http_request(prompt: str) -> requests.Response: 17 | """Sending Request to SEMIKONG 8b FastAPI Endpoint 18 | 19 | Args: 20 | prompt (str): the input prompt 21 | 22 | Returns: 23 | requests.Response: the response of the request 24 | """ 25 | payload = { 26 | "prompt": prompt, 27 | "max_tokens": 100, 28 | "temperature": 0, 29 | "presence_penalty": 0.5, 30 | "frequency_penalty": 0.5, 31 | "top_p": 0, 32 | "top_k": -1, 33 | "min_p": 0.7, 34 | "n": 1, 35 | "best_of": 1, 36 | "stream": True, 37 | } 38 | response = requests.post(BASE_URL, headers=HEADERS, json=payload, stream=True) 39 | return response 40 | 41 | 42 | def get_streaming_response(response: requests.Response) -> Iterable[List[str]]: 43 | for chunk in response.iter_lines( 44 | chunk_size=8192, decode_unicode=False, delimiter=b"\0" 45 | ): 46 | if chunk: 47 | data = json.loads(chunk.decode("utf-8")) 48 | output = data["text"] 49 | 50 | return output 51 | 52 | 53 | def post_process(response_output: str): 54 | clean_text = response_output.split("") 55 | return clean_text[-1] 56 | 57 | 58 | def main(): 59 | logger = logging.getLogger(__name__) 60 | logging.basicConfig(filename="data.log", encoding="utf-8", level=logging.DEBUG) 61 | 62 | prompt_input = str(input("Input your prompt: ")) 63 | 64 | logger.info("Start inferencing ....") 65 | start = time.time() 66 | response = post_http_request(prompt_input) 67 | output = get_streaming_response(response)[0] # only 1 output as list 68 | output = post_process(output) 69 | logger.info(f"Take {time.time() - start} seconds time finish") 70 | logger.info("Finish inferencing") 71 | 72 | with open("output.txt", "a") as file: 73 | file.write(f'Total tokens: {len(output.split(" "))} \n\n') 74 | file.write(f"Answer: {output} \n\n") 75 | file.write("----------------------------------- \n\n") 76 | 77 | 78 | if __name__ == "__main__": 79 | main() 80 | -------------------------------------------------------------------------------- /logging_setup.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | import asyncio 3 | import logging 4 | import os 5 | import sys 6 | 7 | import coloredlogs 8 | from loguru import logger 9 | 10 | if os.name == 'nt': 11 | asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy()) 12 | 13 | logger.remove() 14 | logger.add(sys.stderr, level=logging.ERROR) 15 | 16 | 17 | class InterceptHandler(logging.Handler): 18 | """Intercept standard logging messages toward your Loguru sinks. 19 | Code was taken from https://github.com/Delgan/loguru#entirely-compatible-with-standard-logging""" 20 | 21 | loggers = {} 22 | 23 | def emit(self, record): 24 | # Get corresponding Loguru level if it exists 25 | try: 26 | level = logger.level(record.levelname).name 27 | except ValueError: 28 | level = record.levelno 29 | 30 | # Find caller from where originated the logged message 31 | frame, depth = sys._getframe(2), 2 32 | while frame.f_code.co_filename == logging.__file__: 33 | frame = frame.f_back 34 | depth += 1 35 | 36 | if record.name not in self.loggers: 37 | self.loggers[record.name] = logger.bind(name=record.name) 38 | self.loggers[record.name].opt(depth=depth, exception=record.exc_info).log(level, record.getMessage()) 39 | 40 | 41 | coloredlogs.DEFAULT_LEVEL_STYLES = { 42 | **coloredlogs.DEFAULT_LEVEL_STYLES, 43 | 'critical': {'background': 'red'}, 44 | 'debug': coloredlogs.DEFAULT_LEVEL_STYLES['info'], 45 | } 46 | 47 | log_level = logging.DEBUG if os.environ.get('PRODUCTION', False) == 'DEBUG' else logging.INFO 48 | if isinstance(log_level, str): 49 | log_level = logging.INFO 50 | 51 | format_string = '%(asctime)s | %(name)s | %(levelname)s | %(message)s' 52 | 53 | coloredlogs.install(stream=sys.stdout, level=log_level, fmt=format_string) 54 | 55 | logging.basicConfig(level=log_level, format=format_string) 56 | logging.getLogger().addHandler(InterceptHandler(level=log_level)) 57 | 58 | logging.getLogger('github.Requester').setLevel(logging.WARNING) 59 | logging.getLogger('matplotlib').setLevel(logging.WARNING) 60 | logging.getLogger('multipart').setLevel(logging.WARNING) 61 | logging.getLogger('oauth2client').setLevel(logging.WARNING) 62 | logging.getLogger('openai').setLevel(logging.INFO) 63 | logging.getLogger('pdfminer').setLevel(logging.WARNING) 64 | logging.getLogger('PIL').setLevel(logging.WARNING) 65 | logging.getLogger('urllib3').setLevel(logging.WARNING) 66 | logging.getLogger('websockets').setLevel(logging.WARNING) 67 | logging.getLogger('werkzeug').setLevel(logging.WARNING) 68 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | share/python-wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | MANIFEST 28 | 29 | # PyInstaller 30 | # Usually these files are written by a python script from a template 31 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 32 | *.manifest 33 | *.spec 34 | 35 | # Installer logs 36 | pip-log.txt 37 | pip-delete-this-directory.txt 38 | 39 | # Unit test / coverage reports 40 | htmlcov/ 41 | .tox/ 42 | .nox/ 43 | .coverage 44 | .coverage.* 45 | .cache 46 | nosetests.xml 47 | coverage.xml 48 | *.cover 49 | *.py,cover 50 | .hypothesis/ 51 | .pytest_cache/ 52 | cover/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | .pybuilder/ 76 | target/ 77 | 78 | # Jupyter Notebook 79 | .ipynb_checkpoints 80 | 81 | # IPython 82 | profile_default/ 83 | ipython_config.py 84 | 85 | # pyenv 86 | # For a library or package, you might want to ignore these files since the code is 87 | # intended to run in multiple environments; otherwise, check them in: 88 | # .python-version 89 | 90 | # pipenv 91 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 92 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 93 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 94 | # install all needed dependencies. 95 | #Pipfile.lock 96 | 97 | # poetry 98 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. 99 | # This is especially recommended for binary packages to ensure reproducibility, and is more 100 | # commonly ignored for libraries. 101 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control 102 | #poetry.lock 103 | 104 | # pdm 105 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. 106 | #pdm.lock 107 | # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it 108 | # in version control. 109 | # https://pdm.fming.dev/latest/usage/project/#working-with-version-control 110 | .pdm.toml 111 | .pdm-python 112 | .pdm-build/ 113 | 114 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm 115 | __pypackages__/ 116 | 117 | # Celery stuff 118 | celerybeat-schedule 119 | celerybeat.pid 120 | 121 | # SageMath parsed files 122 | *.sage.py 123 | 124 | # Environments 125 | .env 126 | .venv 127 | env/ 128 | venv/ 129 | ENV/ 130 | env.bak/ 131 | venv.bak/ 132 | 133 | # Spyder project settings 134 | .spyderproject 135 | .spyproject 136 | 137 | # Rope project settings 138 | .ropeproject 139 | 140 | # mkdocs documentation 141 | /site 142 | 143 | # mypy 144 | .mypy_cache/ 145 | .dmypy.json 146 | dmypy.json 147 | 148 | # Pyre type checker 149 | .pyre/ 150 | 151 | # pytype static type analyzer 152 | .pytype/ 153 | 154 | # Cython debug symbols 155 | cython_debug/ 156 | 157 | # PyCharm 158 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can 159 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore 160 | # and can be added to the global gitignore or merged into this file. For a more nuclear 161 | # option (not recommended) you can uncomment the following to ignore the entire idea folder. 162 | #.idea/ 163 | -------------------------------------------------------------------------------- /raw_inference.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | import logging 3 | 4 | import torch 5 | import yaml 6 | from peft import LoraConfig, PeftModel 7 | from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig, pipeline 8 | 9 | 10 | def load_config(config_file="./configs/inference-config.yaml"): 11 | """ 12 | Load the configuration from a YAML file. 13 | """ 14 | with open(config_file, 'r') as file: 15 | return yaml.safe_load(file) 16 | 17 | 18 | def configure_bnb_4bit(config): 19 | """ 20 | Configures the 4-bit quantization settings for the model. 21 | """ 22 | compute_dtype = getattr(torch, config["model"]["bnb_4bit_compute_dtype"]) 23 | return BitsAndBytesConfig( 24 | load_in_4bit=config["model"]["use_4bit"], 25 | bnb_4bit_quant_type=config["model"]["bnb_4bit_quant_type"], 26 | bnb_4bit_compute_dtype=compute_dtype, 27 | bnb_4bit_use_double_quant=config["model"]["use_nested_quant"] 28 | ) 29 | 30 | 31 | def load_model_and_tokenizer(config, bnb_config): 32 | """ 33 | Loads the model and tokenizer with the given configuration. 34 | """ 35 | model_name = config["model"]["model_name"] 36 | device_map = config["model"]["device_map"] 37 | 38 | model = AutoModelForCausalLM.from_pretrained( 39 | model_name, 40 | device_map=device_map, 41 | quantization_config=bnb_config 42 | ) 43 | 44 | model.config.use_cache = False 45 | model.config.pretraining_tp = 1 46 | 47 | tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True) 48 | tokenizer.pad_token = tokenizer.eos_token 49 | tokenizer.padding_side = "right" 50 | 51 | return model, tokenizer 52 | 53 | 54 | def configure_lora(config): 55 | """ 56 | Configures the LoRA parameters for model fine-tuning. 57 | """ 58 | lora_params = config["lora"] 59 | return LoraConfig( 60 | lora_alpha=lora_params["lora_alpha"], 61 | lora_dropout=lora_params["lora_dropout"], 62 | r=lora_params["lora_r"], 63 | bias="none", 64 | task_type="CAUSAL_LM", 65 | ) 66 | 67 | 68 | def text_gen_eval_wrapper(model, tokenizer, prompt, max_length=200, temperature=0.7): 69 | """ 70 | A wrapper function for inferencing, generating text based on a prompt. 71 | """ 72 | # Suppress logging 73 | logging.set_verbosity(logging.CRITICAL) 74 | 75 | # Initialize text generation pipeline 76 | pipe = pipeline( 77 | task="text-generation", 78 | model=model, 79 | tokenizer=tokenizer, 80 | max_length=max_length, 81 | do_sample=True, 82 | temperature=temperature 83 | ) 84 | 85 | # Generate text from prompt 86 | result = pipe(f"[INST] {prompt} [/INST]") 87 | generated_text = result[0]['generated_text'] 88 | 89 | # Extract text after the prompt 90 | index = generated_text.find("[/INST] ") 91 | return generated_text[index + len("[/INST] "):].strip() if index != -1 else generated_text.strip() 92 | 93 | 94 | def main(): 95 | # Setup argparse to receive the config file path 96 | parser = argparse.ArgumentParser(description="Model Inference Script") 97 | parser.add_argument("--config", type=str, default="./configs/inference-config.yaml", help="Path to the config file") 98 | 99 | # Parse the arguments 100 | args = parser.parse_args() 101 | 102 | # Load configuration from the file specified by the --config argument 103 | config = load_config(args.config) 104 | 105 | # Configure 4-bit settings 106 | bnb_config = configure_bnb_4bit(config) 107 | 108 | # Load the base model and tokenizer 109 | model, tokenizer = load_model_and_tokenizer(config, bnb_config) 110 | 111 | # Load LoRA configuration and merge it with the model 112 | configure_lora(config) 113 | base_model = AutoModelForCausalLM.from_pretrained( 114 | config["model"]["model_name"], 115 | low_cpu_mem_usage=True, 116 | return_dict=True, 117 | torch_dtype=torch.float16, 118 | device_map=config["model"]["device_map"], 119 | ) 120 | 121 | model = PeftModel.from_pretrained(base_model, config["model"]["output_dir"]) 122 | model = model.merge_and_unload() 123 | 124 | # Perform text generation 125 | prompt = "tell me about different type of etching in semiconductor" 126 | generated_text = text_gen_eval_wrapper(model, tokenizer, prompt, max_length=200, temperature=0.7) 127 | print(generated_text) 128 | 129 | 130 | if __name__ == "__main__": 131 | main() 132 | -------------------------------------------------------------------------------- /training.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | 3 | import torch 4 | import yaml 5 | from datasets import load_dataset 6 | from peft import LoraConfig 7 | from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig, TrainingArguments 8 | from trl import SFTTrainer 9 | 10 | 11 | # Function to load the configuration from YAML file 12 | def load_config(config_file): 13 | with open(config_file, 'r') as file: 14 | return yaml.safe_load(file) 15 | 16 | 17 | # Load model and tokenizer based on configuration 18 | def load_model(config): 19 | compute_dtype = getattr(torch, config["model"]["bnb_4bit_compute_dtype"]) 20 | 21 | bnb_config = BitsAndBytesConfig( 22 | load_in_4bit=config["model"]["use_4bit"], 23 | bnb_4bit_quant_type=config["model"]["bnb_4bit_quant_type"], 24 | bnb_4bit_compute_dtype=compute_dtype, 25 | bnb_4bit_use_double_quant=config["model"]["use_nested_quant"], 26 | ) 27 | 28 | model_name = config["model"]["model_name"] 29 | model = AutoModelForCausalLM.from_pretrained( 30 | model_name, 31 | device_map=config["model"]["device_map"], 32 | quantization_config=bnb_config 33 | ) 34 | 35 | model.config.use_cache = False 36 | model.config.pretraining_tp = 1 37 | 38 | tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True) 39 | tokenizer.pad_token = tokenizer.eos_token 40 | tokenizer.padding_side = "right" 41 | 42 | return model, tokenizer 43 | 44 | 45 | # Configure LoRA settings 46 | def configure_lora(config): 47 | lora_params = config["lora"] 48 | return LoraConfig( 49 | lora_alpha=lora_params["lora_alpha"], 50 | lora_dropout=lora_params["lora_dropout"], 51 | r=lora_params["lora_r"], 52 | bias="none", 53 | task_type="CAUSAL_LM", 54 | ) 55 | 56 | 57 | # Format data into the instruction template 58 | def format_dolly(sample): 59 | instruction = f"[INST] {sample['instruction']}" 60 | context = f"Here's some context: {sample['input']}" if len(sample["input"]) > 0 else None 61 | response = f" [/INST] {sample['output']}" 62 | return "".join([i for i in [instruction, context, response] if i is not None]) 63 | 64 | 65 | # Template dataset mapping 66 | def template_dataset(sample, tokenizer): 67 | sample["text"] = f"{format_dolly(sample)}{tokenizer.eos_token}" 68 | return sample 69 | 70 | 71 | def main(): 72 | # Parse command-line arguments 73 | parser = argparse.ArgumentParser(description="Fine-tune a model with LoRA and 4-bit precision.") 74 | parser.add_argument("--config", type=str, default="config.yaml", help="Path to the YAML config file.") 75 | args = parser.parse_args() 76 | 77 | # Load configuration 78 | config = load_config(args.config) 79 | 80 | # Load model and tokenizer 81 | model, tokenizer = load_model(config) 82 | 83 | # Configure LoRA 84 | peft_config = configure_lora(config) 85 | 86 | # Load and process the dataset 87 | dataset_name = config["model"]["dataset_name"] 88 | dataset = load_dataset("json", data_files=dataset_name, split="train") 89 | dataset = dataset.shuffle(seed=42) 90 | dataset = dataset.select(range(50)) # Optional: select first 50 rows for demo 91 | dataset = dataset.map(lambda sample: template_dataset(sample, tokenizer), remove_columns=list(dataset.features)) 92 | 93 | # Set up training arguments 94 | training_arguments = TrainingArguments( 95 | output_dir=config["model"]["output_dir"], 96 | per_device_train_batch_size=config["training"]["per_device_train_batch_size"], 97 | gradient_accumulation_steps=config["training"]["gradient_accumulation_steps"], 98 | optim=config["training"]["optim"], 99 | save_steps=config["training"]["save_steps"], 100 | logging_steps=config["training"]["logging_steps"], 101 | learning_rate=config["training"]["learning_rate"], 102 | fp16=config["training"]["fp16"], 103 | bf16=config["training"]["bf16"], 104 | max_grad_norm=config["training"]["max_grad_norm"], 105 | max_steps=config["training"]["max_steps"], 106 | warmup_ratio=config["training"]["warmup_ratio"], 107 | group_by_length=config["training"]["group_by_length"], 108 | lr_scheduler_type=config["training"]["lr_scheduler_type"], 109 | ) 110 | 111 | # Initialize and start training 112 | trainer = SFTTrainer( 113 | model=model, 114 | train_dataset=dataset, 115 | peft_config=peft_config, 116 | dataset_text_field="text", 117 | max_seq_length=config["training"]["max_seq_length"], 118 | tokenizer=tokenizer, 119 | args=training_arguments, 120 | packing=config["training"]["packing"], 121 | ) 122 | 123 | trainer.train() 124 | trainer.model.save_pretrained(config["model"]["output_dir"]) 125 | 126 | 127 | if __name__ == "__main__": 128 | main() 129 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |
2 | 3 | 4 | 5 | 6 | specify theme context for images 7 | 8 | 9 |
10 |
11 | 12 |
13 | 14 |
15 | 16 |
17 |

SEMIKONG - The Open Source Foundation Model for Semiconductor Manufacturing Process

18 |
19 |

20 | Dataset and Benchmarks • 🤖 Hugging Face Model 70B-Instruct• 🤖 Hugging Face Model 8B-Instruct 21 |

22 | 23 |

24 | 👩‍🚀 Ask questions or discuss ideas on GitHub 25 |

26 | 27 |

28 | 📝 Check out SemiKong Paper 29 |

30 | 31 | 32 | 33 |
34 | 35 |
36 | 📕 Table of Contents 37 | 38 | - [What is SEMIKONG?](#what-is-semikong) 39 | - [Introduction](#introduction) 40 | - [Key Features](#features) 41 | - [Models](#models) 42 | - [Chat models](#chat-models) 43 | - [How to use SEMIKONG?](#how-to-use-semikong) 44 | - [Quick start](#quick-start) 45 | - [Choose your path](#choose-your-path) 46 | - [pip](#quick-start---pip) 47 | - [docker](#quick-start---docker) 48 | - [Web demo](#web-demo) 49 | - [Fine-tuning](#fine-tuning) 50 | - [Quantization](#quantization) 51 | - [Deployment](#deployment) 52 | - [FAQ](#faq) 53 | - [Learning hub](#learning-hub) 54 | - [Why SEMIKONG?](#why-semikong) 55 | - [Ecosystem](#ecosystem) 56 | - [Upstream](#upstream) 57 | - [Downstream](#downstream) 58 | - [Serving](#serving) 59 | - [Quantization](#quantization-1) 60 | - [Fine-tuning](#fine-tuning-1) 61 | - [API](#api) 62 | - [Benchmarks](#benchmarks) 63 | - [Chat model performance](#chat-model-performance) 64 | - [Tech report](#tech-report) 65 | - [Citation](#citation) 66 | - [Who can use SEMIKONG?](#who-can-use-semikong) 67 | - [Misc.](#misc) 68 | - [Acknowledgements](#acknowledgments) 69 | - [Disclaimer](#disclaimer) 70 | - [License](#license) 71 | 72 |
73 | 74 |
75 | 76 | # What is SEMIKONG? 77 | 78 | ## Introduction 79 | 80 | - 🤖 SEMIKONG is an open-source, industry-specific large language model (LLM) tailored to the semiconductor domain. It aims to address the unique challenges faced by the semiconductor industry, such as the physics and chemistry of semiconductor devices and processes, by incorporating domain-specific knowledge into the model. 81 | 82 | - 🙌 Targeted as a bilingual language model and trained on 3T multilingual corpus, the SEMIKONG series models become one of the strongest LLM worldwide, showing promise in language understanding, commonsense reasoning, reading comprehension, and more. For example, 83 | 84 | - SEMIKONG-8B / 70B-Instruct model . 85 | 86 | - 🙏 (Credits to Llama) Thanks to the Transformer and Llama open-source communities, as they reduce the efforts required to build from scratch and enable the utilization of the same tools within the AI ecosystem. 87 | 88 | 89 | 90 |

[ 91 | Back to top ⬆️ ] 92 |

93 | 94 | ## News 95 | 96 |

[ 97 | Back to top ⬆️ ] 98 |

99 | 100 | ## Key Features 101 | 102 | - First industry-specific LLM for the semiconductor domain 103 | - Trained on a comprehensive semiconductor-related text corpus 104 | - Novel pre-training approach leveraging domain-specific knowledge 105 | - Superior performance compared to general-purpose LLMs on industry-relevant benchmarks 106 | - Serves as a valuable foundation for companies to build proprietary models tailored to their needs 107 | 108 | ## Models 109 | 110 | SEMIKONG models come in multiple sizes and cater to different use cases. You can also fine-tune SEMIKONG models to meet your specific requirements. 111 | 112 | If you want to deploy SEMIKONG models, make sure you meet the [software and hardware requirements](#deployment). 113 | 114 | ### Instruct models 115 | 116 | | Model | Download | 117 | |---|---| 118 | |SEMIKONG-70B-Instruct | • [🤗 Hugging Face](https://huggingface.co/pentagoniac/SEMIKONG-70B) | 119 | |SEMIKONG-8B-Instruct | • [🤗 Hugging Face](https://huggingface.co/pentagoniac/SEMIKONG-8b-GPTQ) | 120 | 121 | 122 | # How to use SEMIKONG? 123 | 124 | - [Quick start](#quick-start) 125 | - [Choose your path](#choose-your-path) 126 | - [pip](#quick-start---pip) 127 | - [docker](#quick-start---docker) 128 | - [Web demo](#web-demo) 129 | - [Fine-tuning](#fine-tuning) 130 | - [Quantization](#quantization) 131 | - [Deployment](#deployment) 132 | - [FAQ](#faq) 133 | - [Learning hub](#learning-hub) 134 | 135 | ## Quick start 136 | 137 | Getting up and running with SEMIKONG models is simple with multiple choices available. 138 | 139 | ### Choose your path 140 | 141 | Select one of the following paths to begin your journey with SEMIKONG! 142 | 143 | #### 🎯 Deploy SEMIKONG locally 144 | 145 | If you prefer to deploy SEMIKONG models locally, 146 | 147 | - 🙋‍♀️ and you have **sufficient** resources (for example, NVIDIA A100 40GB), you can choose one of the following methods: 148 | - [pip](#quick-start---pip) 149 | - [Docker](#quick-start---docker) 150 | 151 | #### 🎯 Not to deploy SEMIKONG locally 152 | 153 | If you prefer not to deploy SEMIKONG models locally, you can explore SEMIKONG's capabilities using any of the following options. 154 | 155 | ##### 🙋‍♀️ Chat with SEMIKONG 156 | 157 | If you want to chat with SEMIKONG, you can use one of these online services, which offer a similar user experience: 158 | 159 | - [SEMIKONG-70B-Instruct](#) (SEMIKONG official on Hugging Face) 160 | 161 |

[ 162 | Back to top ⬆️ ] 163 |

164 | 165 | ### Quick start - pip 166 | 167 | This tutorial guides you through every step of running **SEMIKONG-8B-Instruct locally on an A100 (40G)** and then performing inference. 168 | 169 | #### Step 0: Prerequisites 170 | 171 | - Make sure Python 3.10 or a later version is installed. 172 | 173 | - If you want to run other SEMIKONG models, see [software and hardware requirements](#deployment). 174 | 175 | #### Step 1: Prepare your environment 176 | 177 | To set up the environment and install the required packages, execute the following command. 178 | 179 | ```bash 180 | git clone https://github.com/aitomatic/semikong.git 181 | cd semikong 182 | pip install -r requirements.txt 183 | ``` 184 | 185 | #### Step 2: Download the SEMIKONG model 186 | 187 | You can download the weights and tokenizer of SEMIKONG models from the following sources: 188 | 189 | - [Hugging Face](https://huggingface.co/pentagoniac) 190 | 191 | #### Step 3: Perform inference 192 | 193 | You can perform inference with SEMIKONG chat models as below. 194 | 195 | ##### Perform inference with SEMIKONG chat model 196 | 197 | 1. Create a file named `quick_start.py` and copy the following content to it. 198 | 199 | ```python 200 | from transformers import AutoModelForCausalLM, AutoTokenizer 201 | 202 | model_path = '' 203 | 204 | tokenizer = AutoTokenizer.from_pretrained(model_path, use_fast=False) 205 | 206 | # Since transformers 4.35.0, the GPT-Q/AWQ model can be loaded using AutoModelForCausalLM. 207 | model = AutoModelForCausalLM.from_pretrained( 208 | model_path, 209 | device_map="auto", 210 | torch_dtype='auto' 211 | ).eval() 212 | 213 | # Prompt content: "hi" 214 | messages = [ 215 | {"role": "user", "content": "hi"} 216 | ] 217 | 218 | input_ids = tokenizer.apply_chat_template(conversation=messages, tokenize=True, add_generation_prompt=True, return_tensors='pt') 219 | output_ids = model.generate(input_ids.to('cuda')) 220 | response = tokenizer.decode(output_ids[0][input_ids.shape[1]:], skip_special_tokens=True) 221 | 222 | # Model response: "Hello! How can I assist you today?" 223 | print(response) 224 | ``` 225 | 226 | 2. Run `quick_start.py`. 227 | 228 | ```bash 229 | python quick_start.py 230 | ``` 231 | 232 | Then you can see an output similar to the one below. 🥳 233 | 234 | ```bash 235 | Hello! How can I assist you today? 236 | ``` 237 | 238 |

[ 239 | Back to top ⬆️ ] 240 |

241 | 242 | ### Quick start - Docker 243 | TBA 244 | 245 |

[ 246 | Back to top ⬆️ ] 247 |

248 | 249 | ### Web demo 250 | 251 | You can build a web UI demo for SEMIKONG **chat** models. 252 | 253 | [Step 1: Prepare your environment](#step-1-prepare-your-environment). 254 | 255 | [Step 2: Download the SEMIKONG model](#step-2-download-the-semikong-model). 256 | 257 | Step 3. To start a web service locally, run the following command. 258 | 259 | ```bash 260 | python demo/web_demo.py -c 261 | ``` 262 | 263 | You can access the web UI by entering the address provided in the console into your browser. 264 | 265 |

[ 266 | Back to top ⬆️ ] 267 |

268 | 269 | ### Fine-tuning 270 | 271 | ### Finetune code for SEMIKONG 8B and 70B 272 | 273 | #### Hardware Setup 274 | 275 | For the SEMIKONG-8B model, a node with 1 GPUs, each with GPU memory larger than 16GB, is recommended. 276 | 277 | For the SEMIKONG-70B model, because the usage of the zero-offload technique consumes a lot of CPU memory, please be careful to limit the number of GPUs in the 70B finetune training. Please use CUDA_VISIBLE_DEVICES to limit the number of GPUs (as shown in scripts/run_sft_SEMIKONG_70b.sh). 278 | 279 | A typical hardware setup for finetuning the 70B model is a node with 8 GPUs (limited to 4 in running by CUDA_VISIBLE_DEVICES=0,1,2,3), each with GPU memory larger than 80GB, and total CPU memory larger than 900GB. 280 | 281 | #### Quick Start 282 | 283 | ### Deployment 284 | 285 | If you want to deploy SEMIKONG models, make sure you meet the software and hardware requirements. 286 | 287 | #### Software requirements 288 | 289 | Before using SEMIKONG quantized models, make sure you've installed the correct software listed below. 290 | 291 | | Model | Software 292 | |---|--- 293 | SEMIKONG 4-bit quantized models | [AWQ and CUDA](https://github.com/casper-hansen/AutoAWQ?tab=readme-ov-file#install-from-pypi) 294 | SEMIKONG 8-bit quantized models | [GPTQ and CUDA](https://github.com/PanQiWei/AutoGPTQ?tab=readme-ov-file#quick-installation) 295 | 296 | #### Hardware requirements 297 | 298 | Before deploying SEMIKONG in your environment, make sure your hardware meets the following requirements. 299 | 300 | ##### Instruction models 301 | 302 | | Model | Minimum VRAM | Recommended GPU Example | 303 | |:----------------------|:--------------|:-------------------------------------:| 304 | | SEMIKONG-70B-Instruct | 170 GB | 3 x A100 80GB
5 x A100 40GB | 305 | | SEMIKONG-8B-Instruct | 16 GB | 1 x RTX 3060 (12 GB)
1 x RTX 4060 (8 GB) | 306 | 307 |

[ 308 | Back to top ⬆️ ] 309 |

310 | 311 | 312 | # Why SEMIKONG? 313 | 314 | - [Ecosystem](#ecosystem) 315 | - [Upstream](#upstream) 316 | - [Downstream](#downstream) 317 | - [Serving](#serving) 318 | - [Quantization](#quantization-1) 319 | - [Fine-tuning](#fine-tuning-1) 320 | - [API](#api) 321 | - [Benchmarks](#benchmarks) 322 | - [Chat model performance](#chat-model-performance) 323 | 324 | ## Ecosystem 325 | 326 | SEMIKONG has a comprehensive ecosystem, offering a range of tools, services, and models to enrich your experiences and maximize productivity. 327 | 328 | - [Upstream](#upstream) 329 | - [Downstream](#downstream) 330 | - [Serving](#serving) 331 | - [Quantization](#quantization-1) 332 | - [Fine-tuning](#fine-tuning-1) 333 | - [API](#api) 334 | 335 | ### Upstream 336 | 337 | The SEMIKONG series models follow the same model architecture as Llama. By choosing SEMIKONG, you can leverage existing tools, libraries, and resources within the Llama ecosystem, eliminating the need to create new tools and enhancing development efficiency. 338 | 339 | For example, the SEMIKONG series models are saved in the format of the Llama model. You can directly use `LlamaForCausalLM` and `LlamaTokenizer` to load the model. For more information, see [Use the chat model](#31-use-the-chat-model). 340 | 341 | ```python 342 | from transformers import AutoModelForCausalLM, AutoTokenizer 343 | 344 | tokenizer = AutoTokenizer.from_pretrained("pentagoniac/SEMIKONG-8b-GPTQ", use_fast=False) 345 | 346 | model = AutoModelForCausalLM.from_pretrained("pentagoniac/SEMIKONG-8b-GPTQ", device_map="auto") 347 | ``` 348 | 349 |

[ 350 | Back to top ⬆️ ] 351 |

352 | 353 | ### Downstream 354 | 355 | > 💡 Tip 356 | > 357 | > - Feel free to create a PR and share the fantastic work you've built using the SEMIKONG series models. 358 | > 359 | > - To help others quickly understand your work, it is recommended to use the format of `: + `. 360 | 361 | #### Serving 362 | 363 | If you want to get up with SEMIKONG in a few minutes, you can use the following services built upon SEMIKONG. 364 | 365 | - SEMIKONG-70B-Instruct: you can chat with SEMIKONG using one of the following platforms: 366 | - [SEMIKONG-70B-Instruct | Hugging Face](https://huggingface.co/pentagoniac/SEMIKONG-70B) 367 | - [SEMIKONG-70B-Instruct | SEMIKONG Platform](#): 368 | 369 |

[ 370 | Back to top ⬆️ ] 371 |

372 | 373 | ## Tech report 374 | 375 | For detailed capabilities of the SEMIKONG series model, see [SemiKong Paper](#). 376 | 377 | ### Citation 378 | 379 | ```bibtex 380 | @article{semikong2024, 381 | title={SemiKong: Curating, Training, and Evaluating A Semiconductor Industry-Specific Large Language Model}, 382 | author={Christopher Nguyen, William Nguyen, Atsushi Suzuki, Daisuke Oku, Hong An Phan, Sang Dinh, Zooey Nguyen, Anh Ha, Shruti Raghavan, Huy Vo, Thang Nguyen, Lan Nguyen, Yoshikuni Hirayama}, 383 | journal={arXiv preprint arXiv:2411.13802}, 384 | year={2024} 385 | } 386 | ``` 387 | 388 | ## Benchmarks 389 | 390 | - [Chat model performance](#chat-model-performance) 391 | 392 | ### Chat model performance 393 | 394 | SEMIKONG-70B-Chat model demonstrates exceptional performance, ranking first among all existing open-source models in the benchmarks including MMLU, CMMLU, BBH, GSM8k, and more. 395 | 396 | ![Chat model performance]() 397 | 398 |
399 | Evaluation methods and challenges. ⬇️ 400 |
401 | 402 | # Who can use SEMIKONG? 403 | 404 | Everyone! 🙌 ✅ 405 | 406 | The code and weights of the SEMIKONG series models are distributed under the [Apache 2.0 license](https://github.com/01-ai/SEMIKONG/blob/main/LICENSE), which means the SEMIKONG series models are free for personal usage, academic purposes, and commercial use. 407 | 408 |

[ 409 | Back to top ⬆️ ] 410 |

411 | 412 | # Misc. 413 | 414 | ### Contributions 415 | 416 | This project is the result of a collaborative effort involving multiple companies and individuals: 417 | 418 | - Tokyo Electron: Atsushi Suzuki, Daisuke Oku 419 | - FPT Software AIC: [Huy Vo](https://github.com/sitloboi2012), Thang Nguyen, [Lan Nguyen](https://www.linkedin.com/in/lan-nguyen-b7bb2517/) 420 | - Aitomatic: [William Nguyen](https://github.com/nguyennm1024), [Vinh Luong](https://github.com/LuongTheVinh), [Christopher Nguyen](https://github.com/ctn). 421 | - AI Alliance members and researchers 422 | 423 | We would like to express our gratitude to the AI Alliance (https://thealliance.ai) for providing the impetus, resources, and platform for this work, and for collaboration in open science. We also extend our thanks to the member organizations of the AI Alliance, their researchers and engineers for their valuable contributions to this study, including: 424 | 425 | - Noritaka Yokomori (Tokyo Electron) 426 | - Anthony Annunziata (IBM Research) 427 | - Sean Hughes (ServiceNow) 428 | - Phong Nguyen (FPT Software, AI Center) 429 | 430 | Their expertise, insights, and collaborative spirit have been instrumental in advancing our research. 431 | 432 |

[ 433 | Back to top ⬆️ ] 434 |

435 | 436 | ### Disclaimer 437 | 438 | We use data compliance checking algorithms during the training process, to 439 | ensure the compliance of the trained model to the best of our ability. Due to 440 | complex data and the diversity of language model usage scenarios, we cannot 441 | guarantee that the model will generate correct, and reasonable output in all 442 | scenarios. Please be aware that there is still a risk of the model producing 443 | problematic outputs. We will not be responsible for any risks and issues 444 | resulting from misuse, misguidance, illegal usage, and related misinformation, 445 | as well as any associated data security concerns. 446 | 447 |

[ 448 | Back to top ⬆️ ] 449 |

450 | 451 | ### License 452 | 453 | The code and weights of the SEMIKONG series models are distributed under the [Apache 2.0 license](https://github.com/01-ai/SEMIKONG/blob/main/LICENSE). 454 | 455 | If you create derivative works based on this model, please include the following attribution in your derivative works: 456 | 457 | This work is a derivative of SEMIKONG by AI Alliance, used under the Apache 2.0 License. 458 | 459 |

[ 460 | Back to top ⬆️ ] 461 |

462 | --------------------------------------------------------------------------------