├── opencoconut ├── models │ ├── __init__.py │ ├── _auto.py │ ├── _config.py │ └── qwen2.py ├── __init__.py └── dataset.py ├── examples ├── infer.py ├── train.py └── eval.py ├── setup.py ├── scripts └── parse_synth_gsm8k.py ├── README.md ├── .gitignore └── LICENSE /opencoconut/models/__init__.py: -------------------------------------------------------------------------------- 1 | from ._config import CoconutConfig 2 | from .qwen2 import CoconutQwen2ForCausalLM -------------------------------------------------------------------------------- /opencoconut/__init__.py: -------------------------------------------------------------------------------- 1 | from .dataset import CoTDataset, split_sequences 2 | from .models._auto import AutoCoconutForCausalLM 3 | from .models._config import CoconutConfig -------------------------------------------------------------------------------- /examples/infer.py: -------------------------------------------------------------------------------- 1 | import torch 2 | from transformers import AutoTokenizer, TextStreamer 3 | from opencoconut import AutoCoconutForCausalLM 4 | 5 | def get_device(): 6 | if torch.backends.mps.is_available(): 7 | return "mps" 8 | elif torch.cuda.is_available(): 9 | return "cuda" 10 | else: 11 | return "cpu" 12 | 13 | model_name = "coconut_output_stage3/checkpoint-10000" 14 | 15 | tokenizer = AutoTokenizer.from_pretrained(model_name) 16 | streamer = TextStreamer(tokenizer, skip_prompt=False, skip_special_tokens=False) 17 | 18 | model = AutoCoconutForCausalLM.from_pretrained( 19 | model_name, torch_dtype=torch.bfloat16, device_map=get_device() 20 | ) 21 | model.tokenizer = tokenizer # only for debugging 22 | 23 | prompt = "John cuts his grass to 2 inches. " \ 24 | "It grows .5 inches per month. " \ 25 | "When it gets to 4 inches he cuts it back down to 2 inches. " \ 26 | "It cost $100 to get his grass cut. How much does he pay per year?" 27 | 28 | inputs = tokenizer(prompt, return_tensors="pt").to(model.device) 29 | 30 | outputs = model.generate( 31 | **inputs, 32 | do_sample=True, 33 | max_new_tokens=64, 34 | streamer=streamer, 35 | eos_token_id=tokenizer.eos_token_id, 36 | ) -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | import os 2 | from pathlib import Path 3 | from setuptools import setup, find_packages 4 | 5 | VERSION = "0.0.1" 6 | 7 | common_setup_kwargs = { 8 | "version": VERSION, 9 | "name": "opencoconut", 10 | "author": "Casper Hansen", 11 | "license": "Apache 2.0", 12 | "python_requires": ">=3.8.0", 13 | "description": "OpenCoconut intends to replicate the Chain of Continuous Thought (COCONUT) to implement their novel latent reasoning paradigm.", 14 | "long_description": (Path(__file__).parent / "README.md").read_text( 15 | encoding="UTF-8" 16 | ), 17 | "long_description_content_type": "text/markdown", 18 | "url": "https://github.com/casper-hansen/OpenCoconut", 19 | "keywords": ["opencoconut", "coconut"], 20 | "platforms": ["linux", "windows"], 21 | "classifiers": [ 22 | "Natural Language :: English", 23 | "Programming Language :: Python :: 3.9", 24 | "Programming Language :: Python :: 3.10", 25 | "Programming Language :: Python :: 3.11", 26 | "Programming Language :: Python :: 3.12", 27 | ], 28 | } 29 | 30 | requirements = [ 31 | "torch", 32 | "transformers", 33 | "accelerate", 34 | "datasets", 35 | ] 36 | 37 | setup( 38 | packages=find_packages(), 39 | install_requires=requirements, 40 | **common_setup_kwargs, 41 | ) -------------------------------------------------------------------------------- /opencoconut/models/_auto.py: -------------------------------------------------------------------------------- 1 | from typing import Union 2 | from transformers import AutoConfig, PreTrainedModel 3 | from opencoconut.models import * 4 | 5 | COCONUT_CAUSAL_LM_MODEL_MAP = { 6 | "qwen2": CoconutQwen2ForCausalLM, 7 | } 8 | 9 | 10 | def check_and_get_model_type(model_name_or_path: str, **config_init_kwargs) -> str: 11 | config = AutoConfig.from_pretrained(model_name_or_path, **config_init_kwargs) 12 | if config.model_type not in COCONUT_CAUSAL_LM_MODEL_MAP.keys(): 13 | raise TypeError(f"{config.model_type} isn't supported yet.") 14 | model_type = config.model_type 15 | return model_type 16 | 17 | 18 | class AutoCoconutForCausalLM: 19 | def __init__(self): 20 | raise EnvironmentError( 21 | "You must instantiate AutoCoconutForCausalLM with\n" 22 | "AutoCoconutForCausalLM.from_pretrained" 23 | ) 24 | 25 | @classmethod 26 | def from_pretrained( 27 | cls, 28 | model_path, 29 | config: Union[CoconutConfig] = None, 30 | config_init_kwargs={}, 31 | *args, 32 | **kwargs, 33 | ) -> PreTrainedModel: 34 | model_type = check_and_get_model_type( 35 | model_path, trust_remote_code=True, **config_init_kwargs 36 | ) 37 | 38 | if config is None: 39 | config = CoconutConfig.from_pretrained(model_path) 40 | 41 | model_config = AutoConfig.from_pretrained(model_path, **config_init_kwargs) 42 | model_config.coconut_config = config.to_dict() 43 | 44 | return COCONUT_CAUSAL_LM_MODEL_MAP[model_type].from_pretrained( 45 | model_path, 46 | config=model_config, 47 | *args, 48 | **kwargs, 49 | ) -------------------------------------------------------------------------------- /scripts/parse_synth_gsm8k.py: -------------------------------------------------------------------------------- 1 | # MIT License 2 | # modified from https://github.com/da03/Internalize_CoT_Step_by_Step/blob/main/src/data.py 3 | 4 | import re 5 | from datasets import Dataset, DatasetDict 6 | 7 | def extract_answer(text): 8 | split_pattern = "####" 9 | if split_pattern not in text: 10 | return text.strip().replace(",", "") 11 | else: 12 | _, ans = text.strip().split("####", 1) 13 | ans = "Answer: " + ans.strip() 14 | ans = ans.strip().replace(",", "") 15 | return ans 16 | 17 | 18 | def extract_cot(text): 19 | split_pattern = "####" 20 | if split_pattern not in text: 21 | return None 22 | else: 23 | cot, _ = text.strip().split("####", 1) 24 | cot = cot.strip() 25 | return cot 26 | 27 | file_paths = [ 28 | ("train", "data/train.txt"), 29 | ("valid", "data/valid.txt"), 30 | ("test", "data/test.txt"), 31 | ] 32 | 33 | data = { 34 | "train": [], 35 | "valid": [], 36 | "test": [], 37 | } 38 | 39 | for split, file_path in file_paths: 40 | with open(file_path, encoding="utf-8") as f: 41 | lines = [ 42 | line.strip().split("||") 43 | for line in f.readlines() 44 | if ( 45 | len(line.strip()) > 0 46 | and not line.strip().isspace() 47 | and len(line.strip().split("||")) == 2 48 | ) 49 | ] 50 | 51 | print(split, len(lines)) 52 | 53 | for line in lines: 54 | question, answer_with_steps = line[0], line[1] 55 | cot_steps = extract_cot(answer_with_steps) 56 | if cot_steps is None: 57 | continue 58 | cot_steps = re.findall(r'<<([^<>]+)>>', cot_steps) 59 | answer = extract_answer(answer_with_steps) 60 | data[split].append({ 61 | "question": question, 62 | "cot": cot_steps, 63 | "answer": answer, 64 | }) 65 | 66 | data = { 67 | split: Dataset.from_list(split_data) for split, split_data in data.items() 68 | } 69 | 70 | dataset_dict = DatasetDict(data) 71 | 72 | dataset_dict.push_to_hub("casperhansen/gsm8k_synthetic_cot") 73 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![arXiv](https://img.shields.io/badge/arXiv-2412.06769-b31b1b.svg?style=plastic)](https://arxiv.org/abs/2412.06769) 2 | 3 | # OpenCoconut 4 | 5 | **UPDATE: Meta has finally released their code! It was fun to try and reproduce Coconut, but I am archiving this repository now that the original implementation is up. https://github.com/facebookresearch/coconut** 6 | 7 | OpenCoconut intends to replicate the Chain of Continuous Thought (COCONUT) paper that implements a novel latent reasoning paradigm. The main idea is to generate thoughts in latent space by utilizing the hidden states during prefilling before we start decoding response. We build on the public dataset from the paper for math [casperhansen/gsm8k_synthetic_cot](https://huggingface.co/datasets/casperhansen/gsm8k_synthetic_cot). 8 | 9 | ## Derivative/Similar Work 10 | 11 | 1. Derivative: A clean demonstration of how a modified OpenCoconut using Gemma 2 leads to improved performance in translation tasks: https://github.com/vicksEmmanuel/latent-gemma 12 | 3. Similar: LucidRains implements a custom Transformer from scratch with Coconut paradigm: https://github.com/lucidrains/coconut-pytorch 13 | 14 | ## Getting started 15 | 16 | Install the package and then go look in `examples` for how to run training and inference. 17 | 18 | ``` 19 | git clone https://github.com/casper-hansen/OpenCoconut.git 20 | cd OpenCoconut 21 | pip install -e . 22 | ``` 23 | 24 | If you want to see the thoughts during training or inference, you can run with `DEBUG=1 python ...`. 25 | 26 | ## Future Work 27 | 28 | 1. Improve the loss function 29 | - Use a REINFORCE loss for thought tokens. 30 | 2. Implement COCONUT for pretraining 31 | - Scaling through pretraining would be ideal due to data availability. 32 | 3. Implement early exit with a classifier 33 | - Potentially as simple as training `nn.Linear(X, 1)`. 34 | 4. Improve the datasets 35 | - Find a good mix of step-by-step datasets for math, coding, and general domain. 36 | 5. Adaptively switch between latent and language space during decoding. 37 | - This could help improve accuracy by allowing generation of more thoughts. 38 | 6. Unit testing different parts of the code. 39 | - This should help with keeping bugs in check as code changes. 40 | -------------------------------------------------------------------------------- /opencoconut/models/_config.py: -------------------------------------------------------------------------------- 1 | import os 2 | import json 3 | from typing import Dict 4 | from dataclasses import dataclass, field, asdict 5 | from transformers import PreTrainedTokenizer 6 | from transformers.utils.hub import PushToHubMixin, cached_file 7 | 8 | 9 | @dataclass 10 | class CoconutConfig(PushToHubMixin): 11 | stages: int = field(default=4) 12 | continuous_thoughts: int = field(default=2) 13 | pad_token_id: int = field(default=None) 14 | bot: str = field(default="") 15 | eot: str = field(default="") 16 | bot_id: int = field(default=None) 17 | eot_id: int = field(default=None) 18 | mix_prob: float = field(default=0.3) 19 | 20 | @classmethod 21 | def from_dict(cls, config: Dict = {}): 22 | if not config: 23 | config = cls() 24 | else: 25 | config = cls(**config) 26 | return config 27 | 28 | @classmethod 29 | def from_tokenizer(cls, tokenizer: PreTrainedTokenizer, **kwargs): 30 | """ 31 | Create a CoconutConfig instance from a tokenizer, automatically setting token IDs. 32 | """ 33 | bot = kwargs.pop('bot', '') 34 | eot = kwargs.pop('eot', '') 35 | 36 | # Add special tokens if they don't exist 37 | if bot not in tokenizer.additional_special_tokens: 38 | tokenizer.add_special_tokens({"additional_special_tokens": [bot, eot]}) 39 | 40 | config_dict = { 41 | 'bot': bot, 42 | 'eot': eot, 43 | 'bot_id': tokenizer.convert_tokens_to_ids(bot), 44 | 'eot_id': tokenizer.convert_tokens_to_ids(eot), 45 | 'pad_token_id': tokenizer.pad_token_id, 46 | **kwargs 47 | } 48 | 49 | return cls(**config_dict) 50 | 51 | @classmethod 52 | def from_pretrained(cls, save_dir: str, config_file_name="config.json", **kwargs): 53 | cache_dir = kwargs.pop("cache_dir", None) 54 | force_download = kwargs.pop("force_download", False) 55 | proxies = kwargs.pop("proxies", None) 56 | local_files_only = kwargs.pop("local_files_only", False) 57 | use_auth_token = kwargs.pop("use_auth_token", None) 58 | revision = kwargs.pop("revision", None) 59 | subfolder = kwargs.pop("subfolder", None) 60 | commit_hash = kwargs.pop("_commit_hash", None) 61 | 62 | if os.path.isdir(save_dir): # Local 63 | resolved_config_file = os.path.join(save_dir, config_file_name) 64 | else: # Remote 65 | resolved_config_file = cached_file( 66 | save_dir, 67 | config_file_name, 68 | cache_dir=cache_dir, 69 | force_download=force_download, 70 | proxies=proxies, 71 | use_auth_token=use_auth_token, 72 | revision=revision, 73 | local_files_only=local_files_only, 74 | subfolder=subfolder, 75 | _raise_exceptions_for_missing_entries=False, 76 | _raise_exceptions_for_connection_errors=False, 77 | _commit_hash=commit_hash, 78 | ) 79 | 80 | config = None 81 | if os.path.exists(resolved_config_file): 82 | with open(resolved_config_file, "r", encoding="utf-8") as file: 83 | loaded_config = json.loads(file.read()) 84 | 85 | config = loaded_config.get("coconut_config") 86 | 87 | if config is not None: 88 | config = cls(**config) 89 | 90 | if config is None: 91 | raise AttributeError("No coconut_config attribute found in config.json.") 92 | 93 | return config 94 | 95 | def to_dict(self): 96 | return asdict(self) 97 | 98 | def __repr__(self): 99 | return json.dumps(self.to_dict(), indent=4) -------------------------------------------------------------------------------- /examples/train.py: -------------------------------------------------------------------------------- 1 | import os 2 | import torch 3 | import logging 4 | from transformers import ( 5 | Trainer, 6 | TrainingArguments, 7 | AutoTokenizer, 8 | ) 9 | from opencoconut import ( 10 | AutoCoconutForCausalLM, 11 | CoconutConfig, 12 | CoTDataset, 13 | ) 14 | 15 | # Configure logging 16 | logging.basicConfig( 17 | level=logging.INFO, 18 | format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", 19 | ) 20 | logger = logging.getLogger(__name__) 21 | 22 | 23 | def get_device(): 24 | if torch.backends.mps.is_available(): 25 | return "mps" 26 | elif torch.cuda.is_available(): 27 | return "cuda" 28 | else: 29 | return "cpu" 30 | 31 | 32 | def main(): 33 | # Initialize model and tokenizer 34 | logger.info("Initializing model and tokenizer") 35 | model_name = "Qwen/Qwen2.5-0.5B" 36 | output_dir = "./coconut_output" 37 | 38 | # tokenizer 39 | tokenizer = AutoTokenizer.from_pretrained(model_name) 40 | tokenizer.bos_token = "<|im_start|>" 41 | tokenizer.eos_token = "<|im_end|>" 42 | tokenizer.pad_token = "<|endoftext|>" 43 | 44 | # config and model 45 | config = CoconutConfig.from_tokenizer( 46 | tokenizer, 47 | stages=4, 48 | continuous_thoughts=2, 49 | ) 50 | model = AutoCoconutForCausalLM.from_pretrained( 51 | model_name, config, torch_dtype=torch.bfloat16, device_map=get_device() 52 | ) 53 | model.resize_token_embeddings(len(tokenizer)) 54 | if os.getenv("DEBUG", "0") == "1": 55 | model.tokenizer = tokenizer 56 | 57 | # Set up training arguments 58 | training_args = TrainingArguments( 59 | output_dir=output_dir, 60 | per_device_train_batch_size=1, 61 | gradient_accumulation_steps=1, 62 | learning_rate=1e-4, 63 | warmup_ratio=0.1, 64 | max_steps=1000, 65 | logging_steps=1, 66 | save_steps=10000, 67 | bf16=True, 68 | bf16_full_eval=True, 69 | optim="adamw_torch", # save memory: adamw_bnb_8bit 70 | ) 71 | 72 | # Initialize trainer 73 | for stage in range(config.stages): 74 | logger.info(f"starting stage {stage}") 75 | logger.info("preparing dataset") 76 | dataset = CoTDataset( 77 | "casperhansen/gsm8k_synthetic_cot", 78 | tokenizer, 79 | max_length=512, 80 | coconut_config=config, 81 | current_stage=stage, 82 | ) 83 | logger.info(f"dataset size: {len(dataset)}") 84 | model.current_stage = stage 85 | current_output_dir = f"{output_dir}_stage{stage}" 86 | training_args.output_dir = current_output_dir 87 | 88 | if stage == 0: 89 | training_args.num_train_epochs = 6 90 | elif stage == config.stages-2: 91 | # Penultimate stage removes all the remaining language reasoning chain 92 | # This handles the long-tail distribution of reasoning chains longer than 3 steps 93 | dataset.include_reasoning_steps = False 94 | training_args.num_train_epochs = 3 95 | elif stage == config.stages-1: 96 | # For all datasets, after the standard schedule, 97 | # the model stays in the final training stage, until the 50th epoch. 98 | dataset.include_reasoning_steps = True 99 | training_args.num_train_epochs = 50 100 | 101 | logger.info("starting training") 102 | trainer = Trainer( 103 | model=model, 104 | args=training_args, 105 | train_dataset=dataset, 106 | ) 107 | trainer.train() 108 | 109 | # save tokenizer to all checkpoints after training 110 | for folder in os.listdir(current_output_dir): 111 | if folder.startswith("checkpoint-"): 112 | checkpoint_folder = os.path.join(current_output_dir, folder) 113 | if os.path.isdir(checkpoint_folder): 114 | tokenizer.save_pretrained(checkpoint_folder) 115 | 116 | 117 | if __name__ == "__main__": 118 | main() 119 | -------------------------------------------------------------------------------- /examples/eval.py: -------------------------------------------------------------------------------- 1 | import tqdm 2 | import torch 3 | import argparse 4 | from torch.utils.data import DataLoader 5 | from transformers import ( 6 | AutoTokenizer, 7 | PreTrainedModel, 8 | PreTrainedTokenizer, 9 | ) 10 | 11 | from opencoconut import AutoCoconutForCausalLM, CoTDataset, split_sequences 12 | 13 | 14 | def extract_generated_answer(model_output: str, eos_token="<|im_end|>"): 15 | answer_prefix = "Answer: " 16 | start_index = model_output.find(answer_prefix) 17 | 18 | if start_index == -1: 19 | return None 20 | 21 | start_index += len(answer_prefix) 22 | end_index = model_output.find(eos_token, start_index) 23 | 24 | if end_index == -1: 25 | return None 26 | 27 | extracted_answer = model_output[start_index:end_index].strip() 28 | return extracted_answer 29 | 30 | 31 | @torch.no_grad() 32 | def evaluate( 33 | dataloader, 34 | tokenizer: PreTrainedTokenizer, 35 | model: PreTrainedModel, 36 | max_new_tokens: int, 37 | ): 38 | total_instances = 0 39 | total_correct = 0 40 | for batch in tqdm.tqdm(dataloader): 41 | ( 42 | thought_ids, 43 | language_ids, 44 | thought_mask, 45 | _, 46 | _, 47 | _, 48 | ) = split_sequences(**batch, coconut_config=model.coconut_config) 49 | batch_size = thought_ids.shape[0] 50 | total_instances += batch_size 51 | 52 | # Generate 53 | beam_output = model.generate( 54 | input_ids=thought_ids.to(model.device), 55 | attention_mask=thought_mask.to(model.device), 56 | max_new_tokens=max_new_tokens, 57 | eos_token_id=tokenizer.eos_token_id, 58 | pad_token_id=tokenizer.pad_token_id, 59 | ) 60 | # Evaluate 61 | for thought_ids_batch, output_batch in zip(thought_ids, beam_output): 62 | decoded_language_ids = tokenizer.decode(language_ids[0]) 63 | decoded_pred_text = tokenizer.decode(output_batch) 64 | answer = extract_generated_answer( 65 | decoded_language_ids, eos_token=tokenizer.eos_token 66 | ) 67 | pred_answer = extract_generated_answer( 68 | decoded_pred_text, eos_token=tokenizer.eos_token 69 | ) 70 | if answer == pred_answer: 71 | total_correct += 1 72 | print( 73 | f"Input: {tokenizer.decode(thought_ids_batch, skip_special_tokens=True)}\n" 74 | f"Target: {answer}\n" 75 | f"Predicted: {pred_answer}\n" 76 | ) 77 | accuracy = total_correct / total_instances 78 | return accuracy 79 | 80 | 81 | def get_device(): 82 | if torch.backends.mps.is_available(): 83 | return "mps" 84 | elif torch.cuda.is_available(): 85 | return "cuda" 86 | else: 87 | return "cpu" 88 | 89 | 90 | def main(): 91 | parser = argparse.ArgumentParser() 92 | parser.add_argument("--model_name", type=str, default=None) 93 | parser.add_argument("--max_new_tokens", type=int, default=512) 94 | parser.add_argument("--batch_size", type=int, default=1) 95 | args = parser.parse_args() 96 | 97 | tokenizer = AutoTokenizer.from_pretrained(args.model_name) 98 | 99 | # Load model 100 | model = AutoCoconutForCausalLM.from_pretrained( 101 | args.model_name, torch_dtype=torch.bfloat16, device_map=get_device() 102 | ) 103 | model.tokenizer = tokenizer 104 | model.eval() 105 | 106 | # Load data 107 | dataset = CoTDataset( 108 | "casperhansen/gsm8k_synthetic_cot", 109 | tokenizer, 110 | max_length=args.max_new_tokens, 111 | coconut_config=model.coconut_config, 112 | current_stage=model.coconut_config.stages, 113 | split="valid", 114 | ) 115 | dataloader = DataLoader(dataset, batch_size=args.batch_size, shuffle=False) 116 | accuracy = evaluate(dataloader, tokenizer, model, args.max_new_tokens) 117 | print(f"Accuracy: {accuracy}") 118 | 119 | 120 | if __name__ == "__main__": 121 | main() 122 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | coconut_output* 2 | # Byte-compiled / optimized / DLL files 3 | __pycache__/ 4 | *.py[cod] 5 | *$py.class 6 | 7 | # C extensions 8 | *.so 9 | 10 | # Distribution / packaging 11 | .Python 12 | build/ 13 | develop-eggs/ 14 | dist/ 15 | downloads/ 16 | eggs/ 17 | .eggs/ 18 | lib/ 19 | lib64/ 20 | parts/ 21 | sdist/ 22 | var/ 23 | wheels/ 24 | share/python-wheels/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | MANIFEST 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .nox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | *.py,cover 51 | .hypothesis/ 52 | .pytest_cache/ 53 | cover/ 54 | 55 | # Translations 56 | *.mo 57 | *.pot 58 | 59 | # Django stuff: 60 | *.log 61 | local_settings.py 62 | db.sqlite3 63 | db.sqlite3-journal 64 | 65 | # Flask stuff: 66 | instance/ 67 | .webassets-cache 68 | 69 | # Scrapy stuff: 70 | .scrapy 71 | 72 | # Sphinx documentation 73 | docs/_build/ 74 | 75 | # PyBuilder 76 | .pybuilder/ 77 | target/ 78 | 79 | # Jupyter Notebook 80 | .ipynb_checkpoints 81 | 82 | # IPython 83 | profile_default/ 84 | ipython_config.py 85 | 86 | # pyenv 87 | # For a library or package, you might want to ignore these files since the code is 88 | # intended to run in multiple environments; otherwise, check them in: 89 | # .python-version 90 | 91 | # pipenv 92 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 93 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 94 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 95 | # install all needed dependencies. 96 | #Pipfile.lock 97 | 98 | # UV 99 | # Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control. 100 | # This is especially recommended for binary packages to ensure reproducibility, and is more 101 | # commonly ignored for libraries. 102 | #uv.lock 103 | 104 | # poetry 105 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. 106 | # This is especially recommended for binary packages to ensure reproducibility, and is more 107 | # commonly ignored for libraries. 108 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control 109 | #poetry.lock 110 | 111 | # pdm 112 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. 113 | #pdm.lock 114 | # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it 115 | # in version control. 116 | # https://pdm.fming.dev/latest/usage/project/#working-with-version-control 117 | .pdm.toml 118 | .pdm-python 119 | .pdm-build/ 120 | 121 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm 122 | __pypackages__/ 123 | 124 | # Celery stuff 125 | celerybeat-schedule 126 | celerybeat.pid 127 | 128 | # SageMath parsed files 129 | *.sage.py 130 | 131 | # Environments 132 | .env 133 | .venv 134 | env/ 135 | venv/ 136 | ENV/ 137 | env.bak/ 138 | venv.bak/ 139 | 140 | # Spyder project settings 141 | .spyderproject 142 | .spyproject 143 | 144 | # Rope project settings 145 | .ropeproject 146 | 147 | # mkdocs documentation 148 | /site 149 | 150 | # mypy 151 | .mypy_cache/ 152 | .dmypy.json 153 | dmypy.json 154 | 155 | # Pyre type checker 156 | .pyre/ 157 | 158 | # pytype static type analyzer 159 | .pytype/ 160 | 161 | # Cython debug symbols 162 | cython_debug/ 163 | 164 | # PyCharm 165 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can 166 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore 167 | # and can be added to the global gitignore or merged into this file. For a more nuclear 168 | # option (not recommended) you can uncomment the following to ignore the entire idea folder. 169 | #.idea/ 170 | 171 | # PyPI configuration file 172 | .pypirc 173 | -------------------------------------------------------------------------------- /opencoconut/dataset.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import random 3 | from datasets import load_dataset 4 | from torch.utils.data import Dataset 5 | from transformers import PreTrainedTokenizer 6 | 7 | # NOTE: cannot support \n between eos1 and bot yet 8 | CHATML_LIKE_FORMAT = "{bos}\n{question}{eos}{bot}{eot}\n{cot_steps}\n{answer}{eos}" 9 | 10 | 11 | class CoTDataset(Dataset): 12 | def __init__( 13 | self, 14 | dataset_name: str, 15 | tokenizer: PreTrainedTokenizer, 16 | coconut_config, 17 | current_stage=0, 18 | max_length=512, 19 | include_reasoning_steps=True, 20 | prompt_format=CHATML_LIKE_FORMAT, 21 | split="train", 22 | ): 23 | self.dataset = load_dataset(dataset_name, split=split) 24 | self.tokenizer = tokenizer 25 | self.max_length = max_length 26 | self.prompt_format = prompt_format 27 | self.coconut_config = coconut_config 28 | self.current_stage = current_stage 29 | self.include_reasoning_steps = include_reasoning_steps 30 | 31 | def __len__(self): 32 | return len(self.dataset) 33 | 34 | def __getitem__(self, idx): 35 | item = self.dataset[idx] 36 | 37 | # Decide whether to use the current stage or a different stage 38 | if random.random() < self.coconut_config.mix_prob and self.current_stage != 0: 39 | # Choose a random stage (excluding the current stage, which is self.k) 40 | self.current_stage = random.choice( 41 | [ 42 | i 43 | for i in range(1, self.coconut_config.stages, 1) 44 | if i != self.current_stage 45 | ] 46 | ) 47 | else: 48 | self.current_stage = self.current_stage # Use the current stage 49 | 50 | prompt_formatted = self.prompt_format.format( 51 | bos=self.tokenizer.bos_token, 52 | question=item["question"], 53 | eos=self.tokenizer.eos_token, 54 | bot=self.coconut_config.bot, 55 | eot=self.coconut_config.eot, 56 | cot_steps=( 57 | "\n".join(item["cot"][self.current_stage :]) 58 | if self.include_reasoning_steps 59 | else "" 60 | ), 61 | answer=item["answer"], 62 | ) 63 | 64 | tokenized = self.tokenizer.encode_plus( 65 | prompt_formatted, 66 | max_length=self.max_length, 67 | add_special_tokens=True, 68 | padding="max_length", 69 | truncation=True, 70 | return_tensors="pt", 71 | ) 72 | 73 | input_ids = tokenized["input_ids"].squeeze(0) 74 | attention_mask = tokenized["attention_mask"].squeeze(0) 75 | labels = input_ids.clone() 76 | 77 | # Mask question and thought tokens 78 | eot_positions = (input_ids == self.coconut_config.eot_id).nonzero( 79 | as_tuple=True 80 | )[0] 81 | if len(eot_positions) > 0: 82 | eot_pos = eot_positions[0] # Position of the first token 83 | labels[: eot_pos + 1] = -100 # Mask up to and including 84 | 85 | # Mask padding tokens using attention_mask 86 | labels[attention_mask == 0] = -100 87 | 88 | return { 89 | "input_ids": input_ids, 90 | "attention_mask": attention_mask, 91 | "labels": labels, 92 | } 93 | 94 | 95 | def split_sequences( 96 | input_ids: torch.Tensor, 97 | attention_mask: torch.Tensor, 98 | labels: torch.Tensor, 99 | coconut_config, 100 | ): 101 | """Split input_ids, attention_mask, and labels based on and token positions. 102 | 103 | Args: 104 | input_ids: Input IDs tensor. 105 | attention_mask: Attention mask tensor. 106 | labels: Labels tensor. 107 | tokenizer: Tokenizer for padding. 108 | bot_id: Token ID for . 109 | eot_id: Token ID for . 110 | """ 111 | if input_ids.dim() == 1: 112 | input_ids = input_ids.unsqueeze(0) 113 | attention_mask = attention_mask.unsqueeze(0) 114 | labels = labels.unsqueeze(0) 115 | 116 | batch_size = len(input_ids) 117 | latent_ids = [] 118 | language_ids = [] 119 | latent_mask = [] 120 | language_mask = [] 121 | latent_labels = [] 122 | language_labels = [] 123 | 124 | for i in range(batch_size): 125 | # Find positions of delimiter tokens in input_ids 126 | bot_positions = (input_ids[i] == coconut_config.bot_id).nonzero(as_tuple=True)[ 127 | 0 128 | ] 129 | eot_positions = (input_ids[i] == coconut_config.eot_id).nonzero(as_tuple=True)[ 130 | 0 131 | ] 132 | 133 | if len(bot_positions) > 0 and len(eot_positions) > 0: 134 | # Take first occurrence of each token 135 | bot_pos = bot_positions[0] 136 | eot_pos = eot_positions[0] 137 | 138 | # Split input_ids 139 | latent_ids.append(input_ids[i][: bot_pos + 1]) 140 | language_ids.append(input_ids[i][eot_pos:]) 141 | 142 | # Split attention_mask 143 | latent_mask.append(attention_mask[i][: bot_pos + 1]) 144 | language_mask.append(attention_mask[i][eot_pos:]) 145 | 146 | # Split labels 147 | latent_labels.append(labels[i][: bot_pos + 1]) 148 | language_labels.append(labels[i][eot_pos:]) 149 | 150 | # Pad sequences 151 | latent_ids = torch.nn.utils.rnn.pad_sequence( 152 | latent_ids, batch_first=True, padding_value=coconut_config.pad_token_id 153 | ) 154 | language_ids = torch.nn.utils.rnn.pad_sequence( 155 | language_ids, batch_first=True, padding_value=coconut_config.pad_token_id 156 | ) 157 | latent_mask = torch.nn.utils.rnn.pad_sequence( 158 | latent_mask, batch_first=True, padding_value=0 159 | ) 160 | language_mask = torch.nn.utils.rnn.pad_sequence( 161 | language_mask, batch_first=True, padding_value=0 162 | ) 163 | latent_labels = torch.nn.utils.rnn.pad_sequence( 164 | latent_labels, batch_first=True, padding_value=-100 165 | ) 166 | language_labels = torch.nn.utils.rnn.pad_sequence( 167 | language_labels, batch_first=True, padding_value=-100 168 | ) 169 | 170 | return ( 171 | latent_ids, 172 | language_ids, 173 | latent_mask, 174 | language_mask, 175 | latent_labels, 176 | language_labels, 177 | ) 178 | 179 | 180 | if __name__ == "__main__": 181 | from transformers import AutoTokenizer 182 | from opencoconut import CoconutConfig 183 | 184 | model_name = "Qwen/Qwen2.5-0.5B" 185 | 186 | tokenizer = AutoTokenizer.from_pretrained(model_name) 187 | tokenizer.bos_token = "<|im_start|>" 188 | tokenizer.eos_token = "<|im_end|>" 189 | tokenizer.pad_token = "<|endoftext|>" 190 | 191 | config = CoconutConfig.from_tokenizer( 192 | tokenizer, 193 | stages=4, 194 | continuous_thoughts=2, 195 | ) 196 | dataset = CoTDataset( 197 | "casperhansen/gsm8k_synthetic_cot", 198 | tokenizer, 199 | max_length=512, 200 | coconut_config=config, 201 | current_stage=3, 202 | ) 203 | batch = next(iter(dataset)) 204 | ( 205 | thought_ids, 206 | language_ids, 207 | thought_mask, 208 | language_mask, 209 | thought_labels, 210 | language_labels, 211 | ) = split_sequences(**batch, coconut_config=config) 212 | 213 | formatted_output = " ".join( 214 | f"<{id}> ({mask})" 215 | for id, mask in zip(language_ids[0].tolist(), language_mask[0].tolist()) 216 | ) 217 | print(formatted_output) 218 | print(tokenizer.decode(thought_ids[0]), end="") 219 | print( 220 | tokenizer.decode(language_ids[0]).replace(tokenizer.pad_token, "") 221 | ) # NOTE: avoid printing all the padding tokens 222 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /opencoconut/models/qwen2.py: -------------------------------------------------------------------------------- 1 | import os 2 | import torch 3 | import logging 4 | from typing import Optional, List, Union 5 | from transformers import ( 6 | Qwen2ForCausalLM, 7 | DynamicCache, 8 | PreTrainedTokenizer, 9 | ) 10 | from . import CoconutConfig 11 | from ..dataset import split_sequences 12 | 13 | logger = logging.getLogger(__name__) 14 | 15 | 16 | class CoconutQwen2ForCausalLM(Qwen2ForCausalLM): 17 | def __init__(self, config): 18 | super().__init__(config) 19 | self.tokenizer: PreTrainedTokenizer = None 20 | self.coconut_config: CoconutConfig = CoconutConfig.from_dict( 21 | config.coconut_config 22 | ) 23 | self.current_stage = 0 24 | self.debug = os.environ.get("DEBUG") == "1" 25 | 26 | def thoughts_forward( 27 | self, 28 | num_thoughts, 29 | inputs_embeds, 30 | attention_mask, 31 | past_key_values, 32 | ): 33 | all_thought_outputs = [] 34 | 35 | for t in range(num_thoughts): 36 | outputs = self.model.forward( 37 | attention_mask=attention_mask, 38 | past_key_values=past_key_values, 39 | inputs_embeds=inputs_embeds, 40 | use_cache=True, 41 | return_dict=True, 42 | ) 43 | 44 | # The inputs for the next thought will be the current hidden state 45 | inputs_embeds = outputs.last_hidden_state[:, -1:, :] 46 | attention_mask = torch.cat( 47 | ( 48 | attention_mask, 49 | torch.ones( 50 | (inputs_embeds.shape[0], 1), 51 | dtype=attention_mask.dtype, 52 | device=attention_mask.device, 53 | ), 54 | ), 55 | dim=1, 56 | ) 57 | past_key_values = outputs.past_key_values 58 | 59 | if self.debug: 60 | all_thought_outputs.append( 61 | self.hidden_states_to_token(inputs_embeds, lm_head=True) 62 | ) 63 | 64 | return all_thought_outputs 65 | 66 | def infer_forward( 67 | self, 68 | input_ids: torch.LongTensor = None, 69 | attention_mask: Optional[torch.Tensor] = None, 70 | position_ids: Optional[torch.LongTensor] = None, 71 | past_key_values: Optional[Union[DynamicCache, List[torch.FloatTensor]]] = None, 72 | inputs_embeds: Optional[torch.FloatTensor] = None, 73 | labels: Optional[torch.LongTensor] = None, 74 | use_cache: Optional[bool] = None, 75 | output_attentions: Optional[bool] = None, 76 | output_hidden_states: Optional[bool] = None, 77 | return_dict: Optional[bool] = None, 78 | cache_position: Optional[torch.LongTensor] = None, 79 | num_logits_to_keep: int = 0, 80 | **loss_kwargs, 81 | ): 82 | output_attentions = ( 83 | output_attentions 84 | if output_attentions is not None 85 | else self.config.output_attentions 86 | ) 87 | output_hidden_states = ( 88 | output_hidden_states 89 | if output_hidden_states is not None 90 | else self.config.output_hidden_states 91 | ) 92 | return_dict = ( 93 | return_dict if return_dict is not None else self.config.use_return_dict 94 | ) 95 | batch_size = input_ids.shape[0] 96 | 97 | if input_ids.shape[1] > 1: 98 | input_ids = torch.concat( 99 | [ 100 | input_ids, 101 | torch.tensor( 102 | [[self.coconut_config.bot_id]] * batch_size, 103 | device=input_ids.device, 104 | ), 105 | ], 106 | dim=1, 107 | ) 108 | attention_mask = torch.concat( 109 | [ 110 | attention_mask, 111 | torch.ones( 112 | attention_mask.shape[0], 1, device=attention_mask.device 113 | ), 114 | ], 115 | dim=1, 116 | ) 117 | 118 | if past_key_values is None: 119 | past_key_values = DynamicCache() 120 | 121 | # NOTE: only generate thoughts in the prefilling phase 122 | if self.coconut_config.stages - 1 > 0 and input_ids.shape[1] > 1: 123 | num_thoughts = ( 124 | (self.coconut_config.stages - 1) * self.coconut_config.continuous_thoughts 125 | ) 126 | inputs_embeds = self.get_input_embeddings()(input_ids) 127 | 128 | all_thought_outputs = self.thoughts_forward( 129 | num_thoughts, inputs_embeds, attention_mask, past_key_values 130 | ) 131 | 132 | inputs_embeds = self.get_input_embeddings()( 133 | torch.tensor( 134 | [[self.coconut_config.eot_id]] * batch_size, 135 | device=inputs_embeds.device, 136 | ) 137 | ) 138 | 139 | new_attention_mask = [] 140 | for b in range(batch_size): 141 | new_attention_mask.append( 142 | torch.cat( 143 | ( 144 | attention_mask[b], 145 | torch.ones( 146 | num_thoughts - 1, 147 | dtype=attention_mask.dtype, 148 | device=attention_mask.device, 149 | ), 150 | ) 151 | ) 152 | ) 153 | attention_mask = torch.stack(new_attention_mask, dim=0) 154 | 155 | # Forward pass with combined embeddings 156 | outputs = super().forward( 157 | input_ids=None, 158 | attention_mask=attention_mask, 159 | position_ids=None, 160 | past_key_values=past_key_values, 161 | inputs_embeds=inputs_embeds, 162 | labels=labels, 163 | use_cache=True, 164 | output_attentions=output_attentions, 165 | output_hidden_states=True, 166 | return_dict=True, 167 | num_logits_to_keep=num_logits_to_keep, 168 | ) 169 | 170 | if self.debug: 171 | self._print_thought_and_final_tokens( 172 | outputs.logits, all_thought_outputs 173 | ) 174 | 175 | else: 176 | # Standard forward pass 177 | outputs = super().forward( 178 | input_ids=input_ids, 179 | attention_mask=attention_mask, 180 | position_ids=position_ids, 181 | past_key_values=past_key_values, 182 | inputs_embeds=None, 183 | labels=labels, 184 | use_cache=use_cache, 185 | output_attentions=output_attentions, 186 | output_hidden_states=output_hidden_states, 187 | return_dict=True, 188 | cache_position=cache_position, 189 | num_logits_to_keep=num_logits_to_keep, 190 | **loss_kwargs, 191 | ) 192 | 193 | return outputs 194 | 195 | def train_forward( 196 | self, 197 | input_ids: torch.LongTensor = None, 198 | attention_mask: Optional[torch.Tensor] = None, 199 | position_ids: Optional[torch.LongTensor] = None, 200 | past_key_values: Optional[Union[DynamicCache, List[torch.FloatTensor]]] = None, 201 | inputs_embeds: Optional[torch.FloatTensor] = None, 202 | labels: Optional[torch.LongTensor] = None, 203 | use_cache: Optional[bool] = None, 204 | output_attentions: Optional[bool] = None, 205 | output_hidden_states: Optional[bool] = None, 206 | return_dict: Optional[bool] = None, 207 | cache_position: Optional[torch.LongTensor] = None, 208 | num_logits_to_keep: int = 0, 209 | **loss_kwargs, 210 | ): 211 | output_attentions = ( 212 | output_attentions 213 | if output_attentions is not None 214 | else self.config.output_attentions 215 | ) 216 | output_hidden_states = ( 217 | output_hidden_states 218 | if output_hidden_states is not None 219 | else self.config.output_hidden_states 220 | ) 221 | return_dict = ( 222 | return_dict if return_dict is not None else self.config.use_return_dict 223 | ) 224 | 225 | # Split sequences into thought and language parts 226 | ( 227 | thought_ids, 228 | language_ids, 229 | thought_mask, 230 | _, 231 | _, 232 | language_labels, 233 | ) = split_sequences(input_ids, attention_mask, labels, self.coconut_config) 234 | 235 | all_thought_outputs = [] 236 | 237 | if past_key_values is None: 238 | past_key_values = DynamicCache() 239 | 240 | if self.current_stage > 0: 241 | num_thoughts = self.current_stage * self.coconut_config.continuous_thoughts 242 | inputs_embeds = self.get_input_embeddings()(thought_ids) 243 | 244 | all_thought_outputs = self.thoughts_forward( 245 | num_thoughts, inputs_embeds, thought_mask, past_key_values 246 | ) 247 | 248 | inputs_embeds = self.get_input_embeddings()(language_ids) 249 | 250 | # we fix the mask and labels lengths by inserting between 251 | insert_indices = (input_ids == self.coconut_config.eot_id).nonzero( 252 | as_tuple=True 253 | )[1] 254 | 255 | new_attention_mask = [] 256 | new_labels = [] 257 | for b in range(input_ids.shape[0]): 258 | insert_idx = insert_indices[b] 259 | new_attention_mask.append( 260 | torch.cat( 261 | ( 262 | attention_mask[b, :insert_idx], 263 | torch.ones( 264 | num_thoughts - 1, 265 | dtype=attention_mask.dtype, 266 | device=attention_mask.device, 267 | ), 268 | attention_mask[b, insert_idx:], 269 | ) 270 | ) 271 | ) 272 | 273 | new_labels.append( 274 | torch.cat( 275 | ( 276 | labels[b, :insert_idx], 277 | torch.full( 278 | (num_thoughts - 1,), 279 | -100, 280 | dtype=labels.dtype, 281 | device=labels.device, 282 | ), 283 | labels[b, insert_idx:], 284 | ) 285 | ) 286 | ) 287 | 288 | # Stack the attention masks and labels along the batch dimension 289 | attention_mask = torch.stack(new_attention_mask, dim=0) 290 | labels = torch.stack(new_labels, dim=0) 291 | 292 | # FIXME: cannot reuse past_key_values from generating thoughts 293 | past_key_values = DynamicCache() 294 | 295 | # Forward pass with combined embeddings 296 | outputs = super().forward( 297 | input_ids=None, 298 | attention_mask=attention_mask, 299 | position_ids=None, 300 | past_key_values=past_key_values, 301 | inputs_embeds=inputs_embeds, 302 | labels=language_labels, 303 | use_cache=True, 304 | output_attentions=output_attentions, 305 | output_hidden_states=True, 306 | return_dict=True, 307 | cache_position=cache_position, 308 | num_logits_to_keep=num_logits_to_keep, 309 | ) 310 | 311 | if self.debug: 312 | tokens = [] 313 | for i, (id, mask, label) in enumerate( 314 | zip( 315 | input_ids[0].tolist(), 316 | attention_mask[0].tolist(), 317 | labels[0].tolist(), 318 | ) 319 | ): 320 | tokens.append(f"<{self.tokenizer.decode(id)}> ({mask}, {label})") 321 | if i == insert_idx: 322 | tokens.append(f"<[LATENT THOUGHT]> ({mask}, {label})") 323 | print(" ".join(tokens)) 324 | self._print_thought_and_final_tokens( 325 | outputs.logits, all_thought_outputs 326 | ) 327 | else: 328 | # Standard forward pass 329 | outputs = super().forward( 330 | input_ids=input_ids, 331 | attention_mask=attention_mask, 332 | position_ids=position_ids, 333 | past_key_values=past_key_values, 334 | inputs_embeds=None, 335 | labels=labels, 336 | use_cache=use_cache, 337 | output_attentions=output_attentions, 338 | output_hidden_states=output_hidden_states, 339 | return_dict=True, 340 | cache_position=cache_position, 341 | num_logits_to_keep=num_logits_to_keep, 342 | **loss_kwargs, 343 | ) 344 | 345 | return outputs 346 | 347 | def forward( 348 | self, 349 | input_ids: torch.LongTensor = None, 350 | attention_mask: Optional[torch.Tensor] = None, 351 | position_ids: Optional[torch.LongTensor] = None, 352 | past_key_values: Optional[Union[DynamicCache, List[torch.FloatTensor]]] = None, 353 | inputs_embeds: Optional[torch.FloatTensor] = None, 354 | labels: Optional[torch.LongTensor] = None, 355 | use_cache: Optional[bool] = None, 356 | output_attentions: Optional[bool] = None, 357 | output_hidden_states: Optional[bool] = None, 358 | return_dict: Optional[bool] = None, 359 | cache_position: Optional[torch.LongTensor] = None, 360 | num_logits_to_keep: int = 0, 361 | **loss_kwargs, 362 | ): 363 | if self.training: 364 | forward_fn = self.train_forward 365 | else: 366 | forward_fn = self.infer_forward 367 | 368 | outputs = forward_fn( 369 | input_ids=input_ids, 370 | attention_mask=attention_mask, 371 | position_ids=position_ids, 372 | past_key_values=past_key_values, 373 | inputs_embeds=inputs_embeds, 374 | labels=labels, 375 | use_cache=use_cache, 376 | output_attentions=output_attentions, 377 | output_hidden_states=output_hidden_states, 378 | return_dict=return_dict, 379 | cache_position=cache_position, 380 | num_logits_to_keep=num_logits_to_keep, 381 | **loss_kwargs, 382 | ) 383 | 384 | return outputs 385 | 386 | @torch.no_grad() 387 | def hidden_states_to_token(self, logits: torch.Tensor, lm_head=False): 388 | if lm_head: 389 | logits = self.lm_head(logits) 390 | probs = torch.nn.functional.softmax(logits[:, -1, :], dim=-1) 391 | top_probs, top_indices = torch.topk(probs, 3) 392 | 393 | tokens = [] 394 | 395 | for prob, token_id in zip(top_probs.squeeze(), top_indices.squeeze()): 396 | tokens.append( 397 | { 398 | "token": self.tokenizer.decode(token_id.item()), 399 | "prob": prob.item(), 400 | "token_id": token_id.item(), 401 | } 402 | ) 403 | 404 | return tokens 405 | 406 | def _print_thought_and_final_tokens( 407 | self, logits: torch.Tensor, all_thought_outputs: List[torch.Tensor] 408 | ): 409 | final_thoughts = [] 410 | final_token = self.hidden_states_to_token(logits)[0] 411 | for i, sampled_tokens in enumerate(all_thought_outputs): 412 | tokens_formatted = [] 413 | for j, token in enumerate(sampled_tokens): 414 | tokens_formatted.append( 415 | f"t_{i},{j}: [{token['token'].strip()}] (p: {token['prob']:.3f})" 416 | ) 417 | final_thoughts.append((" || ").join(tokens_formatted)) 418 | print("\n".join(final_thoughts)) 419 | print( 420 | f"t_final: [{final_token['token'].strip()}] (p: {final_token['prob']:.3f})" 421 | ) 422 | --------------------------------------------------------------------------------