diff --git a/README.md b/README.md index ce4b78b..1f7366c 100644 --- a/README.md +++ b/README.md @@ -39,16 +39,17 @@ ## Introduction -InternLM2.5 series are released with the following features: +InternLM3 has open-sourced an 8-billion parameter instruction model, InternLM3-8B-Instruct, designed for general-purpose usage and advanced reasoning. This model has the following characteristics: -- **Outstanding reasoning capability**: State-of-the-art performance on Math reasoning, surpassing models like Llama3 and Gemma2-9B. - -- **1M Context window**: Nearly perfect at finding needles in the haystack with 1M-long context, with leading performance on long-context tasks like LongBench. Try it with [LMDeploy](./chat/lmdeploy.md) for 1M-context inference. More details and a file chat demo are found [here](./long_context/README.md). - -- **Stronger tool use**: InternLM2.5 supports gathering information from more than 100 web pages, corresponding implementation will be released in [Lagent](https://github.com/InternLM/lagent/tree/main) soon. InternLM2.5 has better tool utilization-related capabilities in instruction following, tool selection and reflection. See [examples](./agent/). +- **Enhanced performance at reduced cost**: + State-of-the-art performance on reasoning and knowledge-intensive tasks surpass models like Llama3.1-8B and Qwen2.5-7B. Remarkably, InternLM3 is trained on only 4 trillion high-quality tokens, saving more than 75% of the training cost compared to other LLMs of similar scale. +- **Deep thinking capability**: + InternLM3 supports both the deep thinking mode for solving complicated reasoning tasks via the long chain-of-thought and the normal response mode for fluent user interactions. ## News +\[2025.01.15\] We release InternLM3-8B-Instruct, See [model zoo below](#model-zoo) for download or [model cards](./model_cards/) for more details. + \[2024.08.01\] We release InternLM2.5-1.8B, InternLM2.5-1.8B-Chat, InternLM2.5-20B and InternLM2.5-20B-Chat. See [model zoo below](#model-zoo) for download or [model cards](./model_cards/) for more details. \[2024.07.19\] We release the InternLM2-Reward series of reward models in 1.8B, 7B and 20B sizes. See [model zoo below](#model-zoo) for download or [model cards](./model_cards/internlm2_reward.md) for more details. @@ -69,8 +70,17 @@ InternLM2.5 series are released with the following features: ## Model Zoo +### InternLM3 + +| Model | Transformers(HF) | ModelScope(HF) | Modelers(HF) | Release Date | +| ------------------------- | -------------------------------------------------------- | ------------------------------------------------------ | ----------------------------------------------------- | ------------ | +| **InternLM3-8B-Instruct** | [🤗internlm3_8B_instruct](https://huggingface.co/internlm/internlm3-8b-instruct) | [ internlm3_8b_instruct](https://www.modelscope.cn/models/Shanghai_AI_Laboratory/internlm3-8b-instruct/summary) | [![Open in Modelers](<>)](https://modelers.cn/models/Intern/internlm3-8b-instruct) | 2025-01-15 | + ### InternLM2.5 +
+ (click to expand) + | Model | Transformers(HF) | ModelScope(HF) | OpenXLab(HF) | OpenXLab(Origin) | Release Date | | -------------------------- | ------------------------------------------ | ---------------------------------------- | -------------------------------------- | ------------------------------------------ | ------------ | | **InternLM2.5-1.8B** | [🤗internlm2_5-1_8b](https://huggingface.co/internlm/internlm2_5-1_8b) | [ internlm2_5-1_8b](https://modelscope.cn/models/Shanghai_AI_Laboratory/internlm2_5-1_8b/summary) | [![Open in OpenXLab](https://cdn-static.openxlab.org.cn/header/openxlab_models.svg)](https://openxlab.org.cn/models/detail/OpenLMLab/internlm2_5-1_8b) | [![Open in OpenXLab](https://cdn-static.openxlab.org.cn/header/openxlab_models.svg)](https://openxlab.org.cn/models/detail/OpenLMLab/internlm2_5-1_8b-original) | 2024-08-05 | @@ -93,8 +103,13 @@ The release of InternLM2.5 series contains 1.8B, 7B, and 20B versions. 7B models **Supplements:** `HF` refers to the format used by HuggingFace in [transformers](https://github.com/huggingface/transformers), whereas `Origin` denotes the format adopted by the InternLM team in [InternEvo](https://github.com/InternLM/InternEvo). +
+ ### InternLM2-Reward +
+ (click to expand) + InternLM2-Reward is a series of reward models, trained on 2.4 million preference samples, available in 1.8B, 7B, and 20B sizes. These model were applied to the PPO training process of our chat models. See [model cards](./model_cards/internlm2_reward.md) for more details. | Model | RewardBench Score | Transformers(HF) | ModelScope(HF) | OpenXLab(HF) | Release Date | @@ -103,6 +118,8 @@ InternLM2-Reward is a series of reward models, trained on 2.4 million preference | **InternLM2-7B-Reward** | 86.6 | [🤗internlm2-7b-reward](https://huggingface.co/internlm/internlm2-7b-reward) | [ internlm2-7b-reward](https://modelscope.cn/models/Shanghai_AI_Laboratory/internlm2-7b-reward/summary) | [![Open in OpenXLab](https://cdn-static.openxlab.org.cn/header/openxlab_models.svg)](https://openxlab.org.cn/models/detail/OpenLMLab/internlm2-7b-reward) | 2024-07-19 | | **InternLM2-20B-Reward** | 89.5 | [🤗internlm2-20b-reward](https://huggingface.co/internlm/internlm2-20b-reward) | [ internlm2-20b-reward](https://modelscope.cn/models/Shanghai_AI_Laboratory/internlm2-20b-reward/summary) | [![Open in OpenXLab](https://cdn-static.openxlab.org.cn/header/openxlab_models.svg)](https://openxlab.org.cn/models/detail/OpenLMLab/internlm2-20b-reward) | 2024-07-19 | +
+ ### InternLM2
@@ -128,36 +145,32 @@ Our previous generation models with advanced capabilities in long-context proces ## Performance -We have evaluated InternLM2.5 on several important benchmarks using the open-source evaluation tool [OpenCompass](https://github.com/open-compass/opencompass). Some of the evaluation results are shown in the table below. You are welcome to visit the [OpenCompass Leaderboard](https://rank.opencompass.org.cn) for more evaluation results. +We conducted a comprehensive evaluation of InternLM using the open-source evaluation tool [OpenCompass](https://github.com/internLM/OpenCompass/). The evaluation covered five dimensions of capabilities: disciplinary competence, language competence, knowledge competence, inference competence, and comprehension competence. Here are some of the evaluation results, and you can visit the [OpenCompass leaderboard](https://rank.opencompass.org.cn) for more evaluation results. -### Base Model +| Benchmark | | InternLM3-8B-Instruct | Qwen2.5-7B-Instruct | Llama3.1-8B-Instruct | GPT-4o-mini(close source) | +| ------------ | ------------------------------- | --------------------- | ------------------- | -------------------- | ------------------------- | +| General | CMMLU(0-shot) | **83.1** | 75.8 | 53.9 | 66.0 | +| | MMLU(0-shot) | 76.6 | **76.8** | 71.8 | 82.7 | +| | MMLU-Pro(0-shot) | **57.6** | 56.2 | 48.1 | 64.1 | +| Reasoning | GPQA-Diamond(0-shot) | **37.4** | 33.3 | 24.2 | 42.9 | +| | DROP(0-shot) | **83.1** | 80.4 | 81.6 | 85.2 | +| | HellaSwag(10-shot) | **91.2** | 85.3 | 76.7 | 89.5 | +| | KOR-Bench(0-shot) | **56.4** | 44.6 | 47.7 | 58.2 | +| MATH | MATH-500(0-shot) | **83.0**\* | 72.4 | 48.4 | 74.0 | +| | AIME2024(0-shot) | **20.0**\* | 16.7 | 6.7 | 13.3 | +| Coding | LiveCodeBench(2407-2409 Pass@1) | **17.8** | 16.8 | 12.9 | 21.8 | +| | HumanEval(Pass@1) | 82.3 | **85.4** | 72.0 | 86.6 | +| Instrunction | IFEval(Prompt-Strict) | **79.3** | 71.7 | 75.2 | 79.7 | +| Long Context | RULER(4-128K Average) | 87.9 | 81.4 | **88.5** | 90.7 | +| Chat | AlpacaEval 2.0(LC WinRate) | **51.1** | 30.3 | 25.0 | 50.7 | +| | WildBench(Raw Score) | **33.1** | 23.3 | 1.5 | 40.3 | +| | MT-Bench-101(Score 1-10) | **8.59** | 8.49 | 8.37 | 8.87 | -| Benchmark | InternLM2.5-7B | Llama3-8B | Yi-1.5-9B | -| -------------- | -------------- | --------- | --------- | -| MMLU (5-shot) | **71.6** | 66.4 | 71.6 | -| CMMLU (5-shot) | **79.1** | 51.0 | 74.1 | -| BBH (3-shot) | 70.1 | 59.7 | 71.1 | -| MATH (4-shot) | **34.0** | 16.4 | 31.9 | -| GSM8K (4-shot) | **74.8** | 54.3 | 74.5 | -| GPQA (0-shot) | **31.3** | 31.3 | 27.8 | +- The evaluation results were obtained from [OpenCompass](https://github.com/internLM/OpenCompass/) (some data marked with \*, which means evaluating with Thinking Mode), and evaluation configuration can be found in the configuration files provided by [OpenCompass](https://github.com/internLM/OpenCompass/). +- The evaluation data may have numerical differences due to the version iteration of [OpenCompass](https://github.com/internLM/OpenCompass/), so please refer to the latest evaluation results of [OpenCompass](https://github.com/internLM/OpenCompass/). + **Limitations:** Although we have made efforts to ensure the safety of the model during the training process and to encourage the model to generate text that complies with ethical and legal requirements, the model may still produce unexpected outputs due to its size and probabilistic generation paradigm. For example, the generated responses may contain biases, discrimination, or other harmful content. Please do not propagate such content. We are not responsible for any consequences resulting from the dissemination of harmful information. -### Chat Model - -| Benchmark | InternLM2.5-7B-Chat | Llama3-8B-Instruct | Gemma2-9B-IT | Yi-1.5-9B-Chat | GLM-4-9B-Chat | Qwen2-7B-Instruct | -| ------------------ | ------------------- | ------------------ | ------------ | -------------- | ------------- | ----------------- | -| MMLU (5-shot) | **72.8** | 68.4 | 70.9 | 71.0 | 71.4 | 70.8 | -| CMMLU (5-shot) | 78.0 | 53.3 | 60.3 | 74.5 | 74.5 | 80.9 | -| BBH (3-shot CoT) | **71.6** | 54.4 | 68.2\* | 69.6 | 69.6 | 65.0 | -| MATH (0-shot CoT) | **60.1** | 27.9 | 46.9 | 51.1 | 51.1 | 48.6 | -| GSM8K (0-shot CoT) | 86.0 | 72.9 | 88.9 | 80.1 | 85.3 | 82.9 | -| GPQA (0-shot) | **38.4** | 26.1 | 33.8 | 37.9 | 36.9 | 38.4 | - -- We use `ppl` for the MCQ evaluation on base model. -- The evaluation results were obtained from [OpenCompass](https://github.com/open-compass/opencompass) , and evaluation configuration can be found in the configuration files provided by [OpenCompass](https://github.com/open-compass/opencompass). -- The evaluation data may have numerical differences due to the version iteration of [OpenCompass](https://github.com/open-compass/opencompass), so please refer to the latest evaluation results of [OpenCompass](https://github.com/open-compass/opencompass). -- \* means the result is copied from the original paper. - -## Requirements +### Requirements - Python >= 3.8 - PyTorch >= 1.12.0 (2.0.0 and above are recommended) @@ -165,56 +178,17 @@ We have evaluated InternLM2.5 on several important benchmarks using the open-sou ## Usages -InternLM supports a diverse range of well-known upstream and downstream projects, such as LLaMA-Factory, vLLM, llama.cpp, and more. This support enables a broad spectrum of users to utilize the InternLM series models more efficiently and conveniently. Tutorials for selected ecosystem projects are available [here](./ecosystem/README.md) for your convenience. +### Conversation Mode -In the following chapters, we will focus on the usages with [Transformers](#import-from-transformers), [ModelScope](#import-from-modelscope), and [Web demos](#dialogue). -The chat models adopt [chatml format](./chat/chat_format.md) to support both chat and agent applications. -To ensure a better usage effect, please make sure that the installed transformers library version meets the following requirements before performing inference with [Transformers](#import-from-transformers) or [ModelScope](#import-from-modelscope): +#### Transformers inference -``` -transformers >= 4.48 -``` - -### Import from Transformers - -To load the InternLM3-8B-Instruct model using Transformers, use the following code: +To load the InternLM3 8B Instruct model using Transformers, use the following code: ```python import torch from transformers import AutoTokenizer, AutoModelForCausalLM -tokenizer = AutoTokenizer.from_pretrained("internlm/internlm3-8b-instruct", trust_remote_code=True) -# Set `torch_dtype=torch.float16` to load model in float16, otherwise it will be loaded as float32 and might cause OOM Error. -model = AutoModelForCausalLM.from_pretrained("internlm/internlm3-8b-instruct", trust_remote_code=True, torch_dtype=torch.float16) -# (Optional) If on low resource devices, you can load model in 4-bit or 8-bit to further save GPU memory via bitsandbytes. - # InternLM3 8B in 4bit will cost nearly 8GB GPU memory. - # pip install -U bitsandbytes - # 8-bit: model = AutoModelForCausalLM.from_pretrained("internlm/internlm3-8b-instruct", device_map="auto", trust_remote_code=True, load_in_8bit=True) - # 4-bit: model = AutoModelForCausalLM.from_pretrained("internlm/internlm3-8b-instruct", device_map="auto", trust_remote_code=True, load_in_4bit=True) -model = model.eval() - -messages = [ - {"role": "system", "content": "You are an AI assistant whose name is InternLM."}, - {"role": "user", "content": "Please tell me five scenic spots in Shanghai"}, - ] -tokenized_chat = tokenizer.apply_chat_template(messages, tokenize=True, add_generation_prompt=True, return_tensors="pt") - -generated_ids = model.generate(tokenized_chat, max_new_tokens=512) - -generated_ids = [ - output_ids[len(input_ids):] for input_ids, output_ids in zip(tokenized_chat, generated_ids) -] -response = tokenizer.batch_decode(generated_ids)[0] -``` - -### Import from ModelScope - -To load the InternLM3-8B-Instruct model using ModelScope, use the following code: - -```python -import torch -from modelscope import snapshot_download, AutoTokenizer, AutoModelForCausalLM -model_dir = snapshot_download('Shanghai_AI_Laboratory/internlm3-8b-instruct') -tokenizer = AutoTokenizer.from_pretrained(model_dir,trust_remote_code=True) +model_dir = "internlm/internlm3-8b-instruct" +tokenizer = AutoTokenizer.from_pretrained(model_dir, trust_remote_code=True) # Set `torch_dtype=torch.float16` to load model in float16, otherwise it will be loaded as float32 and might cause OOM Error. model = AutoModelForCausalLM.from_pretrained(model_dir, trust_remote_code=True, torch_dtype=torch.float16) # (Optional) If on low resource devices, you can load model in 4-bit or 8-bit to further save GPU memory via bitsandbytes. @@ -223,130 +197,248 @@ model = AutoModelForCausalLM.from_pretrained(model_dir, trust_remote_code=True, # 8-bit: model = AutoModelForCausalLM.from_pretrained(model_dir, device_map="auto", trust_remote_code=True, load_in_8bit=True) # 4-bit: model = AutoModelForCausalLM.from_pretrained(model_dir, device_map="auto", trust_remote_code=True, load_in_4bit=True) model = model.eval() - +system_prompt = """You are an AI assistant whose name is InternLM (书生·浦语). +- InternLM (书生·浦语) is a conversational language model that is developed by Shanghai AI Laboratory (上海人工智能实验室). It is designed to be helpful, honest, and harmless. +- InternLM (书生·浦语) can understand and communicate fluently in the language chosen by the user such as English and 中文.""" messages = [ - {"role": "system", "content": "You are an AI assistant whose name is InternLM."}, + {"role": "system", "content": system_prompt}, {"role": "user", "content": "Please tell me five scenic spots in Shanghai"}, ] tokenized_chat = tokenizer.apply_chat_template(messages, tokenize=True, add_generation_prompt=True, return_tensors="pt") - -generated_ids = model.generate(tokenized_chat, max_new_tokens=512) - +generated_ids = model.generate(tokenized_chat, max_new_tokens=1024, temperature=1, repetition_penalty=1.005, top_k=40, top_p=0.8) generated_ids = [ output_ids[len(input_ids):] for input_ids, output_ids in zip(tokenized_chat, generated_ids) ] +prompt = tokenizer.batch_decode(tokenized_chat)[0] +print(prompt) response = tokenizer.batch_decode(generated_ids)[0] +print(response) ``` -### Dialogue +#### LMDeploy inference -You can interact with the InternLM3-8B-Instruct model through a frontend interface by running the following code: +LMDeploy is a toolkit for compressing, deploying, and serving LLM, developed by the MMRazor and MMDeploy teams. ```bash -pip install streamlit -pip install transformers>=4.48 -streamlit run ./chat/web_demo.py +pip install lmdeploy ``` -## Deployment by LMDeploy - -We use [LMDeploy](https://github.com/InternLM/LMDeploy) for fast deployment of InternLM. - -### Inference - -With only 4 lines of codes, you can perform [internlm2_5-7b-chat](https://huggingface.co/internlm/internlm2_5-7b-chat) inference after `pip install lmdeploy`. +You can run batch inference locally with the following python code: ```python -from lmdeploy import pipeline -pipe = pipeline("internlm/internlm2_5-7b-chat") -response = pipe(["Hi, pls intro yourself", "Shanghai is"]) +import lmdeploy +model_dir = "internlm/internlm3-8b-instruct" +pipe = lmdeploy.pipeline(model_dir) +response = pipe("Please tell me five scenic spots in Shanghai") print(response) ``` -To reduce the memory footprint, we offers 4-bit quantized model [internlm2_5-7b-chat-4bit](https://huggingface.co/internlm/internlm2_5-7b-chat-4bit), with which the inference can be conducted as follows: +Or you can launch an OpenAI compatible server with the following command: + +```bash +lmdeploy serve api_server internlm/internlm3-8b-instruct --model-name internlm3-8b-instruct --server-port 23333 +``` + +Then you can send a chat request to the server: + +```bash +curl http://localhost:23333/v1/chat/completions \ + -H "Content-Type: application/json" \ + -d '{ + "model": "internlm3-8b-instruct", + "messages": [ + {"role": "user", "content": "Please tell me five scenic spots in Shanghai"} + ] + }' +``` + +Find more details in the [LMDeploy documentation](https://lmdeploy.readthedocs.io/en/latest/) + +#### Ollama inference + +TODO + +#### vLLM inference + +We are still working on merging the PR(https://github.com/vllm-project/vllm/pull/12037) into vLLM. In the meantime, please use the following PR link to install it manually. ```python -from lmdeploy import pipeline -pipe = pipeline("internlm/internlm2_5-7b-chat-4bit") -response = pipe(["Hi, pls intro yourself", "Shanghai is"]) +git clone -b support-internlm3 https://github.com/RunningLeon/vllm.git +pip install -e . +``` + +inference code: + +```python +from vllm import LLM, SamplingParams +llm = LLM(model="internlm/internlm3-8b-instruct") +sampling_params = SamplingParams(temperature=1, repetition_penalty=1.005, top_k=40, top_p=0.8) +system_prompt = """You are an AI assistant whose name is InternLM (书生·浦语). +- InternLM (书生·浦语) is a conversational language model that is developed by Shanghai AI Laboratory (上海人工智能实验室). It is designed to be helpful, honest, and harmless. +- InternLM (书生·浦语) can understand and communicate fluently in the language chosen by the user such as English and 中文.""" +prompts = [ + { + "role": "system", + "content": system_prompt, + }, + { + "role": "user", + "content": "Please tell me five scenic spots in Shanghai" + }, +] +outputs = llm.chat(prompts, + sampling_params=sampling_params, + use_tqdm=False) +print(outputs) +``` + +### Thinking Mode + +#### Thinking Demo + + + +#### Thinking system prompt + +```python +thinking_system_prompt = """You are an expert mathematician with extensive experience in mathematical competitions. You approach problems through systematic thinking and rigorous reasoning. When solving problems, follow these thought processes: +## Deep Understanding +Take time to fully comprehend the problem before attempting a solution. Consider: +- What is the real question being asked? +- What are the given conditions and what do they tell us? +- Are there any special restrictions or assumptions? +- Which information is crucial and which is supplementary? +## Multi-angle Analysis +Before solving, conduct thorough analysis: +- What mathematical concepts and properties are involved? +- Can you recall similar classic problems or solution methods? +- Would diagrams or tables help visualize the problem? +- Are there special cases that need separate consideration? +## Systematic Thinking +Plan your solution path: +- Propose multiple possible approaches +- Analyze the feasibility and merits of each method +- Choose the most appropriate method and explain why +- Break complex problems into smaller, manageable steps +## Rigorous Proof +During the solution process: +- Provide solid justification for each step +- Include detailed proofs for key conclusions +- Pay attention to logical connections +- Be vigilant about potential oversights +## Repeated Verification +After completing your solution: +- Verify your results satisfy all conditions +- Check for overlooked special cases +- Consider if the solution can be optimized or simplified +- Review your reasoning process +Remember: +1. Take time to think thoroughly rather than rushing to an answer +2. Rigorously prove each key conclusion +3. Keep an open mind and try different approaches +4. Summarize valuable problem-solving methods +5. Maintain healthy skepticism and verify multiple times +Your response should reflect deep mathematical understanding and precise logical thinking, making your solution path and reasoning clear to others. +When you're ready, present your complete solution with: +- Clear problem understanding +- Detailed solution process +- Key insights +- Thorough verification +Focus on clear, logical progression of ideas and thorough explanation of your mathematical reasoning. Provide answers in the same language as the user asking the question, repeat the final answer using a '\\boxed{}' without any units, you have [[8192]] tokens to complete the answer. +""" +``` + +#### Transformers inference + +```python +import torch +from transformers import AutoTokenizer, AutoModelForCausalLM +model_dir = "internlm/internlm3-8b-instruct" +tokenizer = AutoTokenizer.from_pretrained(model_dir, trust_remote_code=True) +# Set `torch_dtype=torch.float16` to load model in float16, otherwise it will be loaded as float32 and might cause OOM Error. +model = AutoModelForCausalLM.from_pretrained(model_dir, trust_remote_code=True, torch_dtype=torch.float16) +# (Optional) If on low resource devices, you can load model in 4-bit or 8-bit to further save GPU memory via bitsandbytes. + # InternLM3 8B in 4bit will cost nearly 8GB GPU memory. + # pip install -U bitsandbytes + # 8-bit: model = AutoModelForCausalLM.from_pretrained(model_dir, device_map="auto", trust_remote_code=True, load_in_8bit=True) + # 4-bit: model = AutoModelForCausalLM.from_pretrained(model_dir, device_map="auto", trust_remote_code=True, load_in_4bit=True) +model = model.eval() +messages = [ + {"role": "system", "content": thinking_system_prompt}, + {"role": "user", "content": "Given the function\(f(x)=\mathrm{e}^{x}-ax - a^{3}\),\n(1) When \(a = 1\), find the equation of the tangent line to the curve \(y = f(x)\) at the point \((1,f(1))\).\n(2) If \(f(x)\) has a local minimum and the minimum value is less than \(0\), determine the range of values for \(a\)."}, + ] +tokenized_chat = tokenizer.apply_chat_template(messages, tokenize=True, add_generation_prompt=True, return_tensors="pt") +generated_ids = model.generate(tokenized_chat, max_new_tokens=8192) +generated_ids = [ + output_ids[len(input_ids):] for input_ids, output_ids in zip(tokenized_chat, generated_ids) +] +prompt = tokenizer.batch_decode(tokenized_chat)[0] +print(prompt) +response = tokenizer.batch_decode(generated_ids)[0] print(response) ``` -Moreover, you can independently activate the 8bit/4bit KV cache feature: +#### LMDeploy inference + +LMDeploy is a toolkit for compressing, deploying, and serving LLM. + +```bash +pip install lmdeploy +``` + +You can run batch inference locally with the following python code: ```python -from lmdeploy import pipeline, TurbomindEngineConfig -pipe = pipeline("internlm/internlm2_5-7b-chat-4bit", - backend_config=TurbomindEngineConfig(quant_policy=8)) -response = pipe(["Hi, pls intro yourself", "Shanghai is"]) +from lmdeploy import pipeline, GenerationConfig, ChatTemplateConfig +model_dir = "internlm/internlm3-8b-instruct" +chat_template_config = ChatTemplateConfig(model_name='internlm3') +pipe = pipeline(model_dir, chat_template_config=chat_template_config) +messages = [ + {"role": "system", "content": thinking_system_prompt}, + {"role": "user", "content": "Given the function\(f(x)=\mathrm{e}^{x}-ax - a^{3}\),\n(1) When \(a = 1\), find the equation of the tangent line to the curve \(y = f(x)\) at the point \((1,f(1))\).\n(2) If \(f(x)\) has a local minimum and the minimum value is less than \(0\), determine the range of values for \(a\)."}, +] +response = pipe(messages, gen_config=GenerationConfig(max_new_tokens=2048)) print(response) ``` -Please refer to the [guidance](./chat/lmdeploy.md) for more usages about model deployment. For additional deployment tutorials, feel free to explore [here](https://github.com/InternLM/LMDeploy). +#### Ollama inference -### 1M-long-context Inference +TODO -By enabling the Dynamic NTK feature of LMDeploy, you can acquire the long-context inference power. +#### vLLM inference -Note: 1M context length requires 4xA100-80G. +We are still working on merging the PR(https://github.com/vllm-project/vllm/pull/12037) into vLLM. In the meantime, please use the following PR link to install it manually. ```python -from lmdeploy import pipeline, GenerationConfig, TurbomindEngineConfig - -backend_config = TurbomindEngineConfig( - rope_scaling_factor=2.5, - session_len=1048576, # 1M context length - max_batch_size=1, - cache_max_entry_count=0.7, - tp=4) # 4xA100-80G. -pipe = pipeline('internlm/internlm2_5-7b-chat-1m', backend_config=backend_config) -prompt = 'Use a long prompt to replace this sentence' -response = pipe(prompt) -print(response) +git clone https://github.com/RunningLeon/vllm.git +pip install -e . ``` -## Agent +inference code -InternLM2.5-Chat models have excellent tool utilization capabilities and can work with function calls in a zero-shot manner. It also supports to conduct analysis by collecting information from more than 100 web pages. See more examples in [agent section](./agent/). - -## Fine-tuning - -Please refer to [finetune docs](./finetune/) for fine-tuning with InternLM. - -**Note:** We have migrated the whole training functionality in this project to [InternEvo](https://github.com/InternLM/InternEvo) for easier user experience, which provides efficient pre-training and fine-tuning infra for training InternLM. - -## Evaluation - -We utilize [OpenCompass](https://github.com/open-compass/opencompass) for model evaluation. In InternLM2.5, we primarily focus on standard objective evaluation, long-context evaluation (needle in a haystack), data contamination assessment, agent evaluation, and subjective evaluation. - -### Objective Evaluation - -To evaluate the InternLM model, please follow the guidelines in the [OpenCompass tutorial](https://opencompass.readthedocs.io/en/latest/get_started/installation.html). Typically, we use `ppl` for multiple-choice questions on the **Base** model and `gen` for all questions on the **Chat** model. - -### Long-Context Evaluation (Needle in a Haystack) - -For the `Needle in a Haystack` evaluation, refer to the tutorial provided in the [documentation](https://github.com/open-compass/opencompass/blob/main/docs/en/advanced_guides/needleinahaystack_eval.md). Feel free to try it out. - -### Data Contamination Assessment - -To learn more about data contamination assessment, please check the [contamination eval](https://opencompass.readthedocs.io/en/latest/advanced_guides/contamination_eval.html). - -### Agent Evaluation - -- To evaluate tool utilization, please refer to [T-Eval](https://github.com/open-compass/T-Eval). -- For code interpreter evaluation, use the [Math Agent Evaluation](agent/README.md) provided in the repository. - -### Subjective Evaluation - -- Please follow the [tutorial](https://opencompass.readthedocs.io/en/latest/advanced_guides/subjective_evaluation.html) for subjective evaluation. - -## Contribution - -We appreciate all the contributors for their efforts to improve and enhance InternLM. Community users are highly encouraged to participate in the project. Please refer to the contribution guidelines for instructions on how to contribute to the project. +```python +from vllm import LLM, SamplingParams +llm = LLM(model="internlm/internlm3-8b-instruct") +sampling_params = SamplingParams(temperature=1, repetition_penalty=1.005, top_k=40, top_p=0.8, max_tokens=8192) +prompts = [ + { + "role": "system", + "content": thinking_system_prompt, + }, + { + "role": "user", + "content": "Given the function\(f(x)=\mathrm{e}^{x}-ax - a^{3}\),\n(1) When \(a = 1\), find the equation of the tangent line to the curve \(y = f(x)\) at the point \((1,f(1))\).\n(2) If \(f(x)\) has a local minimum and the minimum value is less than \(0\), determine the range of values for \(a\)." + }, +] +outputs = llm.chat(prompts, + sampling_params=sampling_params, + use_tqdm=False) +print(outputs) +``` ## License -The code is licensed under Apache-2.0, while model weights are fully open for academic research and also allow **free** commercial usage. To apply for a commercial license, please fill in the [application form (English)](https://wj.qq.com/s2/12727483/5dba/)/[申请表(中文)](https://wj.qq.com/s2/12725412/f7c1/). For other questions or collaborations, please contact . +Code and model weights are licensed under Apache-2.0. ## Citation diff --git a/README_zh-CN.md b/README_zh-CN.md index ca80175..0a06939 100644 --- a/README_zh-CN.md +++ b/README_zh-CN.md @@ -39,14 +39,17 @@ ## 简介 -InternLM2.5 系列模型在本仓库正式发布,具有如下特性: +InternLM3,即书生·浦语大模型第3代,开源了80亿参数,面向通用使用与高阶推理的指令模型(InternLM3-8B-Instruct)。模型具备以下特点: -- 卓越的推理性能:在数学推理方面取得了同量级模型最优精度,超越了 Llama3 和 Gemma2-9B。 -- 有效支持百万字超长上下文:模型在 1 百万字长输入中几乎完美地实现长文“大海捞针”,而且在 LongBench 等长文任务中的表现也达到开源模型中的领先水平。 可以通过 [LMDeploy](./chat/lmdeploy_zh_cn.md) 尝试百万字超长上下文推理。更多内容和文档对话 demo 请查看[这里](./long_context/README_zh-CN.md)。 -- 工具调用能力整体升级:InternLM2.5 支持从上百个网页搜集有效信息进行分析推理,相关实现将于近期开源到 [Lagent](https://github.com/InternLM/lagent/tree/main)。InternLM2.5 具有更强和更具有泛化性的指令理解、工具筛选与结果反思等能力,新版模型可以更可靠地支持复杂智能体的搭建,支持对工具进行有效的多轮调用,完成较复杂的任务。可以查看更多[样例](./agent/)。 +- **更低的代价取得更高的性能**: + 在推理、知识类任务上取得同量级最优性能,超过Llama3.1-8B和Qwen2.5-7B。值得关注的是InternLM3只用了4万亿词元进行训练,对比同级别模型训练成本节省75%以上。 +- **深度思考能力**: + InternLM3支持通过长思维链求解复杂推理任务的深度思考模式,同时还兼顾了用户体验更流畅的通用回复模式。 ## 更新 +\[2025.01.15\] 我们发布了 InternLM3-8B-Instruct 模型。可以在下方的 [模型库](#model-zoo) 进行下载,或者在 [model cards](./model_cards/) 中了解更多细节。 + \[2024.08.01\] 我们发布了 InternLM2.5-1.8B、InternLM2.5-1.8B-Chat、InternLM2.5-20B 和 InternLM2.5-20B-Chat。可以在下方的 [模型库](#model-zoo) 进行下载,或者在 [model cards](./model_cards/) 中了解更多细节。 \[2024.07.19\] 我们发布了 1.8B、7B 和 20B 大小的 InternLM2-Reward 系列奖励模型。可以在下方的 [模型库](#model-zoo) 进行下载,或者在 [model cards](./model_cards/internlm2_reward.md) 中了解更多细节。 @@ -67,8 +70,17 @@ InternLM2.5 系列模型在本仓库正式发布,具有如下特性: ## Model Zoo +### InternLM3 + +| Model | Transformers(HF) | ModelScope(HF) | Modelers(HF) | Release Date | +| ------------------------- | -------------------------------------------------------- | ------------------------------------------------------ | ----------------------------------------------------- | ------------ | +| **InternLM3-8B-Instruct** | [🤗internlm3_8B_instruct](https://huggingface.co/internlm/internlm3-8b-instruct) | [ internlm3_8b_instruct](https://www.modelscope.cn/models/Shanghai_AI_Laboratory/internlm3-8b-instruct/summary) | [![Open in Modelers](<>)](https://modelers.cn/models/Intern/internlm3-8b-instruct) | 2025-01-15 | + ### InternLM2.5 +
+ (click to expand) + | Model | Transformers(HF) | ModelScope(HF) | OpenXLab(HF) | OpenXLab(Origin) | Release Date | | -------------------------- | ------------------------------------------ | ---------------------------------------- | -------------------------------------- | ------------------------------------------ | ------------ | | **InternLM2.5-1.8B** | [🤗internlm2_5-1_8b](https://huggingface.co/internlm/internlm2_5-1_8b) | [ internlm2_5-1_8b](https://modelscope.cn/models/Shanghai_AI_Laboratory/internlm2_5-1_8b/summary) | [![Open in OpenXLab](https://cdn-static.openxlab.org.cn/header/openxlab_models.svg)](https://openxlab.org.cn/models/detail/OpenLMLab/internlm2_5-1_8b) | [![Open in OpenXLab](https://cdn-static.openxlab.org.cn/header/openxlab_models.svg)](https://openxlab.org.cn/models/detail/OpenLMLab/internlm2_5-1_8b-original) | 2024-08-05 | @@ -91,8 +103,13 @@ InternLM2.5 系列模型在本仓库正式发布,具有如下特性: **补充说明:** 上表中的 `HF` 表示对应模型为 HuggingFace 平台提供的 [transformers](https://github.com/huggingface/transformers) 框架格式;`Origin` 则表示对应模型为我们 InternLM 团队的 [InternEvo](https://github.com/InternLM/InternEvo) 框架格式。 +
+ ### InternLM2-Reward +
+ (click to expand) + InternLM2-Reward 是基于 240 万个偏好样本进行训练的奖励模型,有 1.8B、7B 和 20B 大小可供选择。这些模型被用于 InternLM 对话模型的 PPO 训练过程。请参考 [model cards](./model_cards/internlm2_reward.md) 了解更多细节。 | Model | RewardBench Score | Transformers(HF) | ModelScope(HF) | OpenXLab(HF) | Release Date | @@ -101,6 +118,8 @@ InternLM2-Reward 是基于 240 万个偏好样本进行训练的奖励模型, | **InternLM2-7B-Reward** | 86.6 | [🤗internlm2-7b-reward](https://huggingface.co/internlm/internlm2-7b-reward) | [ internlm2-7b-reward](https://modelscope.cn/models/Shanghai_AI_Laboratory/internlm2-7b-reward/summary) | [![Open in OpenXLab](https://cdn-static.openxlab.org.cn/header/openxlab_models.svg)](https://openxlab.org.cn/models/detail/OpenLMLab/internlm2-7b-reward) | 2024-07-19 | | **InternLM2-20B-Reward** | 89.5 | [🤗internlm2-20b-reward](https://huggingface.co/internlm/internlm2-20b-reward) | [ internlm2-20b-reward](https://modelscope.cn/models/Shanghai_AI_Laboratory/internlm2-20b-reward/summary) | [![Open in OpenXLab](https://cdn-static.openxlab.org.cn/header/openxlab_models.svg)](https://openxlab.org.cn/models/detail/OpenLMLab/internlm2-20b-reward) | 2024-07-19 | +
+ ### InternLM2
@@ -126,36 +145,33 @@ InternLM2-Reward 是基于 240 万个偏好样本进行训练的奖励模型, ## 性能 -我们使用开源评测工具 [OpenCompass](https://github.com/open-compass/opencompass) 在几个重要的基准测试中对 InternLM2.5 进行了评测。部分评测结果如下表所示。欢迎访问 [OpenCompass 排行榜](https://rank.opencompass.org.cn) 获取更多评测结果。 +我们使用开源评测工具 [OpenCompass](https://github.com/internLM/OpenCompass/) 从学科综合能力、语言能力、知识能力、推理能力、理解能力五大能力维度对InternLM开展全面评测,部分评测结果如下表所示,欢迎访问[ OpenCompass 榜单 ](https://rank.opencompass.org.cn)获取更多的评测结果。 -### 基座模型 +| 评测集\\模型 | | InternLM3-8B-Instruct | Qwen2.5-7B-Instruct | Llama3.1-8B-Instruct | GPT-4o-mini(close source) | +| ------------ | ------------------------------- | --------------------- | ------------------- | -------------------- | ------------------------- | +| General | CMMLU(0-shot) | **83.1** | 75.8 | 53.9 | 66.0 | +| | MMLU(0-shot) | 76.6 | **76.8** | 71.8 | 82.7 | +| | MMLU-Pro(0-shot) | **57.6** | 56.2 | 48.1 | 64.1 | +| Reasoning | GPQA-Diamond(0-shot) | **37.4** | 33.3 | 24.2 | 42.9 | +| | DROP(0-shot) | **83.1** | 80.4 | 81.6 | 85.2 | +| | HellaSwag(10-shot) | **91.2** | 85.3 | 76.7 | 89.5 | +| | KOR-Bench(0-shot) | **56.4** | 44.6 | 47.7 | 58.2 | +| MATH | MATH-500(0-shot) | **83.0**\* | 72.4 | 48.4 | 74.0 | +| | AIME2024(0-shot) | **20.0**\* | 16.7 | 6.7 | 13.3 | +| Coding | LiveCodeBench(2407-2409 Pass@1) | **17.8** | 16.8 | 12.9 | 21.8 | +| | HumanEval(Pass@1) | 82.3 | **85.4** | 72.0 | 86.6 | +| Instrunction | IFEval(Prompt-Strict) | **79.3** | 71.7 | 75.2 | 79.7 | +| LongContext | RULER(4-128K Average) | 87.9 | 81.4 | **88.5** | 90.7 | +| Chat | AlpacaEval 2.0(LC WinRate) | **51.1** | 30.3 | 25.0 | 50.7 | +| | WildBench(Raw Score) | **33.1** | 23.3 | 1.5 | 40.3 | +| | MT-Bench-101(Score 1-10) | **8.59** | 8.49 | 8.37 | 8.87 | -| Benchmark | InternLM2.5-7B | Llama3-8B | Yi-1.5-9B | -| -------------- | -------------- | --------- | --------- | -| MMLU (5-shot) | **71.6** | 66.4 | 71.6 | -| CMMLU (5-shot) | **79.1** | 51.0 | 74.1 | -| BBH (3-shot) | 70.1 | 59.7 | 71.1 | -| MATH (4-shot) | **34.0** | 16.4 | 31.9 | -| GSM8K (4-shot) | **74.8** | 54.3 | 74.5 | -| GPQA (0-shot) | **31.3** | 31.3 | 27.8 | +- 以上评测结果基于 [OpenCompass](https://github.com/internLM/OpenCompass/) 获得(部分数据标注`*`代表使用深度思考模式进行评测),具体测试细节可参见 [OpenCompass](https://github.com/internLM/OpenCompass/) 中提供的配置文件。 +- 评测数据会因 [OpenCompass](https://github.com/internLM/OpenCompass/) 的版本迭代而存在数值差异,请以 [OpenCompass](https://github.com/internLM/OpenCompass/) 最新版的评测结果为主。 -### 对话模型 +**局限性:** 尽管在训练过程中我们非常注重模型的安全性,尽力促使模型输出符合伦理和法律要求的文本,但受限于模型大小以及概率生成范式,模型可能会产生各种不符合预期的输出,例如回复内容包含偏见、歧视等有害内容,请勿传播这些内容。由于传播不良信息导致的任何后果,本项目不承担责任。 -| Benchmark | InternLM2.5-7B-Chat | Llama3-8B-Instruct | Gemma2-9B-IT | Yi-1.5-9B-Chat | GLM-4-9B-Chat | Qwen2-7B-Instruct | -| ------------------ | ------------------- | ------------------ | ------------ | -------------- | ------------- | ----------------- | -| MMLU (5-shot) | **72.8** | 68.4 | 70.9 | 71.0 | 71.4 | 70.8 | -| CMMLU (5-shot) | 78.0 | 53.3 | 60.3 | 74.5 | 74.5 | 80.9 | -| BBH (3-shot CoT) | **71.6** | 54.4 | 68.2\* | 69.6 | 69.6 | 65.0 | -| MATH (0-shot CoT) | **60.1** | 27.9 | 46.9 | 51.1 | 51.1 | 48.6 | -| GSM8K (0-shot CoT) | 86.0 | 72.9 | 88.9 | 80.1 | 85.3 | 82.9 | -| GPQA (0-shot) | **38.4** | 26.1 | 33.8 | 37.9 | 36.9 | 38.4 | - -- 我们使用 `ppl` 对基座模型进行 MCQ 指标的评测。 -- 评测结果来自 [OpenCompass](https://github.com/open-compass/opencompass) ,评测配置可以在 [OpenCompass](https://github.com/open-compass/opencompass) 提供的配置文件中找到。 -- 由于 [OpenCompass](https://github.com/open-compass/opencompass) 的版本迭代,评测数据可能存在数值差异,因此请参考 [OpenCompass](https://github.com/open-compass/opencompass) 的最新评测结果。 -- \* 表示从原论文中复制而来。 - -## 依赖 +### 依赖 - Python >= 3.8 - PyTorch >= 1.12.0 (推荐 2.0.0 和更高版本) @@ -163,190 +179,267 @@ InternLM2-Reward 是基于 240 万个偏好样本进行训练的奖励模型, ## 使用案例 -InternLM 支持众多知名的上下游项目,如 LLaMA-Factory、vLLM、llama.cpp 等。这种支持使得广大用户群体能够更高效、更方便地使用 InternLM 全系列模型。为方便使用,我们为部分生态系统项目提供了教程,访问[此处](./ecosystem/README_zh-CN.md)即可获取。 +### 常规对话模式 -接下来我们展示使用 [Transformers](#import-from-transformers),[ModelScope](#import-from-modelscope) 和 [Web demo](#dialogue) 进行推理。 -对话模型采用了 [chatml 格式](./chat/chat_format.md) 来支持通用对话和智能体应用。 -为了保障更好的使用效果,在用 [Transformers](#import-from-transformers) 或 [ModelScope](#import-from-modelscope) 进行推理前,请确保安装的 transformers 库版本满足以下要求: +#### Transformers 推理 -``` -transformers >= 4.48 -``` - -### 通过 Transformers 加载 - -通过以下的代码从 Transformers 加载 InternLM3-8B-Instruct 模型 (可修改模型名称替换不同的模型) +通过以下的代码加载 InternLM3 8B Instruct 模型 ```python import torch from transformers import AutoTokenizer, AutoModelForCausalLM -tokenizer = AutoTokenizer.from_pretrained("internlm/internlm2_5-7b-chat", trust_remote_code=True) -# 设置`torch_dtype=torch.float16`来将模型精度指定为torch.float16,否则可能会因为您的硬件原因造成显存不足的问题。 -model = AutoModelForCausalLM.from_pretrained("internlm/internlm3-8b-instruct", trust_remote_code=True, torch_dtype=torch.float16) -# (可选) 如果在低资源设备上,可以通过bitsandbytes加载4-bit或8-bit量化的模型,进一步节省GPU显存. - # 4-bit 量化的 InternLM3 8B 大约会消耗 8GB 显存. - # pip install -U bitsandbytes - # 8-bit: model = AutoModelForCausalLM.from_pretrained("internlm/internlm3-8b-instruct", device_map="auto", trust_remote_code=True, load_in_8bit=True) - # 4-bit: model = AutoModelForCausalLM.from_pretrained("internlm/internlm3-8b-instruct", device_map="auto", trust_remote_code=True, load_in_4bit=True) -model = model.eval() - -messages = [ - {"role": "system", "content": "You are an AI assistant whose name is InternLM."}, - {"role": "user", "content": "Please tell me five scenic spots in Shanghai"}, - ] -tokenized_chat = tokenizer.apply_chat_template(messages, tokenize=True, add_generation_prompt=True, return_tensors="pt") - -generated_ids = model.generate(tokenized_chat, max_new_tokens=512) - -generated_ids = [ - output_ids[len(input_ids):] for input_ids, output_ids in zip(tokenized_chat, generated_ids) -] -response = tokenizer.batch_decode(generated_ids)[0] -``` - -### 通过 ModelScope 加载 - -通过以下的代码从 ModelScope 加载 InternLM2.5-7B-Chat 模型 (可修改模型名称替换不同的模型) - -```python -import torch -from modelscope import snapshot_download, AutoTokenizer, AutoModelForCausalLM -model_dir = snapshot_download('Shanghai_AI_Laboratory/internlm3-8b-instruct') -tokenizer = AutoTokenizer.from_pretrained(model_dir,trust_remote_code=True) -# 设置`torch_dtype=torch.float16`来将模型精度指定为torch.float16,否则可能会因为您的硬件原因造成显存不足的问题。 -model = AutoModelForCausalLM.from_pretrained(model_dir, device_map="auto", trust_remote_code=True, torch_dtype=torch.float16) -# (可选) 如果在低资源设备上,可以通过bitsandbytes加载4-bit或8-bit量化的模型,进一步节省GPU显存. - # 4-bit 量化的 InternLM3 8B 大约会消耗 8GB 显存. +model_dir = "internlm/internlm3-8b-instruct" +tokenizer = AutoTokenizer.from_pretrained(model_dir, trust_remote_code=True) +# Set `torch_dtype=torch.float16` to load model in float16, otherwise it will be loaded as float32 and might cause OOM Error. +model = AutoModelForCausalLM.from_pretrained(model_dir, trust_remote_code=True, torch_dtype=torch.float16) +# (Optional) If on low resource devices, you can load model in 4-bit or 8-bit to further save GPU memory via bitsandbytes. + # InternLM3 8B in 4bit will cost nearly 8GB GPU memory. # pip install -U bitsandbytes # 8-bit: model = AutoModelForCausalLM.from_pretrained(model_dir, device_map="auto", trust_remote_code=True, load_in_8bit=True) # 4-bit: model = AutoModelForCausalLM.from_pretrained(model_dir, device_map="auto", trust_remote_code=True, load_in_4bit=True) +model = model.eval() +system_prompt = """You are an AI assistant whose name is InternLM (书生·浦语). +- InternLM (书生·浦语) is a conversational language model that is developed by Shanghai AI Laboratory (上海人工智能实验室). It is designed to be helpful, honest, and harmless. +- InternLM (书生·浦语) can understand and communicate fluently in the language chosen by the user such as English and 中文.""" messages = [ - {"role": "system", "content": "You are an AI assistant whose name is InternLM."}, + {"role": "system", "content": system_prompt}, {"role": "user", "content": "Please tell me five scenic spots in Shanghai"}, ] tokenized_chat = tokenizer.apply_chat_template(messages, tokenize=True, add_generation_prompt=True, return_tensors="pt") - -generated_ids = model.generate(tokenized_chat, max_new_tokens=512) - +generated_ids = model.generate(tokenized_chat, max_new_tokens=1024, temperature=1, repetition_penalty=1.005, top_k=40, top_p=0.8) generated_ids = [ output_ids[len(input_ids):] for input_ids, output_ids in zip(tokenized_chat, generated_ids) ] +prompt = tokenizer.batch_decode(tokenized_chat)[0] +print(prompt) response = tokenizer.batch_decode(generated_ids)[0] +print(response) ``` -### 通过前端网页对话 +#### LMDeploy 推理 -可以通过以下代码启动一个前端的界面来与 InternLM3-8B-Instruct 模型进行交互 +LMDeploy 是涵盖了 LLM 任务的全套轻量化、部署和服务解决方案。 ```bash -pip install streamlit -pip install transformers>=4.48 -streamlit run ./chat/web_demo.py +pip install lmdeploy ``` -## InternLM 高性能部署 - -我们使用 [LMDeploy](https://github.com/InternLM/LMDeploy) 完成 InternLM 的一键部署。 - -### 推理 - -通过 `pip install lmdeploy` 安装 LMDeploy 之后,只需 4 行代码,就可以实现离线批处理: +你可以使用以下 python 代码进行本地批量推理: ```python -from lmdeploy import pipeline -pipe = pipeline("internlm/internlm2_5-7b-chat") -response = pipe(["Hi, pls intro yourself", "Shanghai is"]) +import lmdeploy +model_dir = "internlm/internlm3-8b-instruct" +pipe = lmdeploy.pipeline(model_dir) +response = pipe(["Please tell me five scenic spots in Shanghai"]) print(response) ``` -为了减少内存占用,我们提供了4位量化模型 [internlm2_5-7b-chat-4bit](https://huggingface.co/internlm/internlm2_5-7b-chat-4bit)。可以按照如下方式推理该模型: +或者你可以使用以下命令启动兼容 OpenAI API 的服务: + +```bash +lmdeploy serve api_server internlm/internlm3-8b-instruct --model-name internlm3-8b-instruct --server-port 23333 +``` + +然后你可以向服务端发起一个聊天请求: + +```bash +curl http://localhost:23333/v1/chat/completions \ + -H "Content-Type: application/json" \ + -d '{ + "model": "internlm3-8b-instruct", + "messages": [ + {"role": "user", "content": "介绍一下深度学习。"} + ] + }' +``` + +更多信息请查看 [LMDeploy 文档](https://lmdeploy.readthedocs.io/en/latest/) + +#### Ollama 推理 + +TODO + +#### vLLM 推理 + +我们还在推动PR(https://github.com/vllm-project/vllm/pull/12037) 合入vllm,现在请使用以下PR链接手动安装 ```python -from lmdeploy import pipeline -pipe = pipeline("internlm/internlm2_5-7b-chat-4bit") -response = pipe(["Hi, pls intro yourself", "Shanghai is"]) +git clone https://github.com/RunningLeon/vllm.git +pip install -e . +``` + +推理代码 + +```python +from vllm import LLM, SamplingParams +llm = LLM(model="internlm/internlm3-8b-instruct") +sampling_params = SamplingParams(temperature=1, repetition_penalty=1.005, top_k=40, top_p=0.8) +system_prompt = """You are an AI assistant whose name is InternLM (书生·浦语). +- InternLM (书生·浦语) is a conversational language model that is developed by Shanghai AI Laboratory (上海人工智能实验室). It is designed to be helpful, honest, and harmless. +- InternLM (书生·浦语) can understand and communicate fluently in the language chosen by the user such as English and 中文.""" +prompts = [ + { + "role": "system", + "content": system_prompt, + }, + { + "role": "user", + "content": "Please tell me five scenic spots in Shanghai" + }, +] +outputs = llm.chat(prompts, + sampling_params=sampling_params, + use_tqdm=False) +print(outputs) +``` + +### 深度思考模式 + +#### 深度思考 Demo + + + +#### 深度思考 system prompt + +```python +thinking_system_prompt = """You are an expert mathematician with extensive experience in mathematical competitions. You approach problems through systematic thinking and rigorous reasoning. When solving problems, follow these thought processes: +## Deep Understanding +Take time to fully comprehend the problem before attempting a solution. Consider: +- What is the real question being asked? +- What are the given conditions and what do they tell us? +- Are there any special restrictions or assumptions? +- Which information is crucial and which is supplementary? +## Multi-angle Analysis +Before solving, conduct thorough analysis: +- What mathematical concepts and properties are involved? +- Can you recall similar classic problems or solution methods? +- Would diagrams or tables help visualize the problem? +- Are there special cases that need separate consideration? +## Systematic Thinking +Plan your solution path: +- Propose multiple possible approaches +- Analyze the feasibility and merits of each method +- Choose the most appropriate method and explain why +- Break complex problems into smaller, manageable steps +## Rigorous Proof +During the solution process: +- Provide solid justification for each step +- Include detailed proofs for key conclusions +- Pay attention to logical connections +- Be vigilant about potential oversights +## Repeated Verification +After completing your solution: +- Verify your results satisfy all conditions +- Check for overlooked special cases +- Consider if the solution can be optimized or simplified +- Review your reasoning process +Remember: +1. Take time to think thoroughly rather than rushing to an answer +2. Rigorously prove each key conclusion +3. Keep an open mind and try different approaches +4. Summarize valuable problem-solving methods +5. Maintain healthy skepticism and verify multiple times +Your response should reflect deep mathematical understanding and precise logical thinking, making your solution path and reasoning clear to others. +When you're ready, present your complete solution with: +- Clear problem understanding +- Detailed solution process +- Key insights +- Thorough verification +Focus on clear, logical progression of ideas and thorough explanation of your mathematical reasoning. Provide answers in the same language as the user asking the question, repeat the final answer using a '\\boxed{}' without any units, you have [[8192]] tokens to complete the answer. +""" +``` + +#### Transformers 推理 + +```python +import torch +from transformers import AutoTokenizer, AutoModelForCausalLM +model_dir = "internlm/internlm3-8b-instruct" +tokenizer = AutoTokenizer.from_pretrained(model_dir, trust_remote_code=True) +# Set `torch_dtype=torch.float16` to load model in float16, otherwise it will be loaded as float32 and might cause OOM Error. +model = AutoModelForCausalLM.from_pretrained(model_dir, trust_remote_code=True, torch_dtype=torch.float16) +# (Optional) If on low resource devices, you can load model in 4-bit or 8-bit to further save GPU memory via bitsandbytes. + # InternLM3 8B in 4bit will cost nearly 8GB GPU memory. + # pip install -U bitsandbytes + # 8-bit: model = AutoModelForCausalLM.from_pretrained(model_dir, device_map="auto", trust_remote_code=True, load_in_8bit=True) + # 4-bit: model = AutoModelForCausalLM.from_pretrained(model_dir, device_map="auto", trust_remote_code=True, load_in_4bit=True) +model = model.eval() +messages = [ + {"role": "system", "content": thinking_system_prompt}, + {"role": "user", "content": "已知函数\(f(x)=\mathrm{e}^{x}-ax - a^{3}\)。\n(1)当\(a = 1\)时,求曲线\(y = f(x)\)在点\((1,f(1))\)处的切线方程;\n(2)若\(f(x)\)有极小值,且极小值小于\(0\),求\(a\)的取值范围。"}, + ] +tokenized_chat = tokenizer.apply_chat_template(messages, tokenize=True, add_generation_prompt=True, return_tensors="pt") +generated_ids = model.generate(tokenized_chat, max_new_tokens=8192) +generated_ids = [ + output_ids[len(input_ids):] for input_ids, output_ids in zip(tokenized_chat, generated_ids) +] +prompt = tokenizer.batch_decode(tokenized_chat)[0] +print(prompt) +response = tokenizer.batch_decode(generated_ids)[0] print(response) ``` -此外,可以同步开启 8bit 或者 4bit KV 在线量化功能: +#### LMDeploy 推理 + +LMDeploy is a toolkit for compressing, deploying, and serving LLM, developed by the MMRazor and MMDeploy teams. + +```bash +pip install lmdeploy +``` + +You can run batch inference locally with the following python code: ```python -from lmdeploy import pipeline, TurbomindEngineConfig -pipe = pipeline("internlm/internlm2_5-7b-chat-4bit", - backend_config=TurbomindEngineConfig(quant_policy=8)) -response = pipe(["Hi, pls intro yourself", "Shanghai is"]) +from lmdeploy import pipeline, GenerationConfig, ChatTemplateConfig +model_dir = "internlm/internlm3-8b-instruct" +chat_template_config = ChatTemplateConfig(model_name='internlm3') +pipe = pipeline(model_dir, chat_template_config=chat_template_config) +messages = [ + {"role": "system", "content": thinking_system_prompt}, + {"role": "user", "content": "已知函数\(f(x)=\mathrm{e}^{x}-ax - a^{3}\)。\n(1)当\(a = 1\)时,求曲线\(y = f(x)\)在点\((1,f(1))\)处的切线方程;\n(2)若\(f(x)\)有极小值,且极小值小于\(0\),求\(a\)的取值范围。"}, +] +response = pipe(messages, gen_config=GenerationConfig(max_new_tokens=2048)) print(response) ``` -更多使用案例可参考[部署指南](./chat/lmdeploy.md),详细的部署教程则可在[这里](https://github.com/InternLM/LMDeploy)找到。 +#### Ollama 推理 -### 1百万字超长上下文推理 +TODO -激活 LMDeploy 的 Dynamic NTK 能力,可以轻松把 internlm2_5-7b-chat 外推到 200K 上下文。 +#### vLLM 推理 -注意: 1M 上下文需要 4xA100-80G。 +我们还在推动PR(https://github.com/vllm-project/vllm/pull/12037) 合入vllm,现在请使用以下PR链接手动安装 ```python -from lmdeploy import pipeline, GenerationConfig, TurbomindEngineConfig - -backend_config = TurbomindEngineConfig( - rope_scaling_factor=2.5, - session_len=1048576, # 1M context length - max_batch_size=1, - cache_max_entry_count=0.7, - tp=4) # 4xA100-80G. -pipe = pipeline('internlm/internlm2_5-7b-chat-1m', backend_config=backend_config) -prompt = 'Use a long prompt to replace this sentence' -response = pipe(prompt) -print(response) +git clone https://github.com/RunningLeon/vllm.git +pip install -e . ``` -## 智能体 +推理代码 -InternLM-2.5-Chat 模型有出色的工具调用性能并具有一定的零样本泛化能力。它支持从上百个网页中搜集信息并进行分析。更多样例可以参考 [agent 目录](./agent/). - -## 微调&训练 - -请参考[微调教程](./finetune/)尝试续训或微调 InternLM2。 - -**注意:** 本项目中的全量训练功能已经迁移到了 [InternEvo](https://github.com/InternLM/InternEvo) 以便用户使用。InternEvo 提供了高效的预训练和微调基建用于训练 InternLM 系列模型。 - -## 评测 - -我们使用 [OpenCompass](https://github.com/open-compass/opencompass) 进行模型评估。在 InternLM2.5 中,我们主要标准客观评估、长文评估(大海捞针)、数据污染评估、智能体评估和主观评估。 - -### 标准客观评测 - -请按照 [OpenCompass 教程](https://opencompass.readthedocs.io/zh-cn/latest/get_started/installation.html) 进行客观评测。我们通常在 Base 模型上使用 ppl 进行多项选择题评测,在 Chat 模型上使用 gen 进行所有问题的答案生成和评测。 - -### 长文评估(大海捞针) - -有关 `大海捞针` 评估的教程,请参阅 [文档](https://github.com/open-compass/opencompass/blob/main/docs/en/advanced_guides/needleinahaystack_eval.md) 中的教程。 - -### 数据污染评估 - -要了解更多关于数据污染评估的信息,请查看 [污染评估](https://opencompass.readthedocs.io/en/latest/advanced_guides/contamination_eval.html)。 - -### 智能体评估 - -- 要评估大模型的工具利用能力,请使用 [T-Eval](https://github.com/open-compass/T-Eval) 进行评测。 -- 对于代码解释器评估,请使用 [gsm-8k-agent](https://github.com/open-compass/opencompass/blob/main/configs/datasets/gsm8k/gsm8k_agent_gen_be1606.py) 提供的配置进行评估。此外,您还需要安装 [Lagent](https://github.com/InternLM/lagent)。 - -### 主观评估 - -- 请按照 [教程](https://opencompass.readthedocs.io/en/latest/advanced_guides/subjective_evaluation.html) 进行主观评估。 - -## 贡献 - -我们感谢所有的贡献者为改进和提升 InternLM 所作出的努力。非常欢迎社区用户能参与进项目中来。请参考贡献指南来了解参与项目贡献的相关指引。 - -## 致谢 - -InternLM 代码库是一款由上海人工智能实验室和来自不同高校、企业的研发人员共同参与贡献的开源项目。我们感谢所有为项目提供新功能支持的贡献者,以及提供宝贵反馈意见的用户。我们希望这个工具箱和基准测试可以为社区提供灵活高效的代码工具,供用户微调 InternLM 并开发自己的新模型,从而不断为开源社区提供贡献。特别鸣谢 [flash-attention](https://github.com/HazyResearch/flash-attention) 与 [ColossalAI](https://github.com/hpcaitech/ColossalAI) 两项开源项目。 +```python +from vllm import LLM, SamplingParams +llm = LLM(model="internlm/internlm3-8b-instruct") +sampling_params = SamplingParams(temperature=1, repetition_penalty=1.005, top_k=40, top_p=0.8, max_tokens=8192) +prompts = [ + { + "role": "system", + "content": thinking_system_prompt, + }, + { + "role": "user", + "content": "已知函数\(f(x)=\mathrm{e}^{x}-ax - a^{3}\)。\n(1)当\(a = 1\)时,求曲线\(y = f(x)\)在点\((1,f(1))\)处的切线方程;\n(2)若\(f(x)\)有极小值,且极小值小于\(0\),求\(a\)的取值范围。" + }, +] +outputs = llm.chat(prompts, + sampling_params=sampling_params, + use_tqdm=False) +print(outputs) +``` ## 开源许可证 -本仓库的代码依照 Apache-2.0 协议开源。模型权重对学术研究完全开放,也可申请免费的商业使用授权([申请表](https://wj.qq.com/s2/12725412/f7c1/))。其他问题与合作请联系 。 +本仓库的代码和权重依照 Apache-2.0 协议开源。 ## 引用