Create Math
Browse files
    	
        Math
    ADDED
    
    | @@ -0,0 +1,24 @@ | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | 
|  | |
| 1 | 
            +
            import torch
         | 
| 2 | 
            +
            from transformers import AutoTokenizer, AutoModelForCausalLM, GenerationConfig
         | 
| 3 | 
            +
             | 
| 4 | 
            +
            # 加载 DeepSeekMath 模型和分词器
         | 
| 5 | 
            +
            model_name = "deepseek-ai/deepseek-math-7b-instruct"
         | 
| 6 | 
            +
            tokenizer = AutoTokenizer.from_pretrained(model_name)
         | 
| 7 | 
            +
            model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype=torch.bfloat16, device_map="auto")
         | 
| 8 | 
            +
            model.generation_config = GenerationConfig.from_pretrained(model_name)
         | 
| 9 | 
            +
            model.generation_config.pad_token_id = model.generation_config.eos_token_id
         | 
| 10 | 
            +
             | 
| 11 | 
            +
            # 定义带有链式推理的数学问题
         | 
| 12 | 
            +
            messages = [
         | 
| 13 | 
            +
                {"role": "user", "content": "what is the integral of x^2 from 0 to 2?\nPlease reason step by step, and put your final answer within \\boxed{}."}
         | 
| 14 | 
            +
            ]
         | 
| 15 | 
            +
             | 
| 16 | 
            +
            # 将问题转换为模型输入格式
         | 
| 17 | 
            +
            input_tensor = tokenizer.apply_chat_template(messages, add_generation_prompt=True, return_tensors="pt")
         | 
| 18 | 
            +
             | 
| 19 | 
            +
            # 生成模型的输出
         | 
| 20 | 
            +
            outputs = model.generate(input_tensor.to(model.device), max_new_tokens=100)
         | 
| 21 | 
            +
             | 
| 22 | 
            +
            # 解码输出并打印结果
         | 
| 23 | 
            +
            result = tokenizer.decode(outputs[0][input_tensor.shape[1]:], skip_special_tokens=True)
         | 
| 24 | 
            +
            print(result)
         |