import logging
from typing import Any

import torch
from torch.utils.data import DataLoader

from mteb.abstasks.task_metadata import TaskMetadata
from mteb.models.model_meta import ModelMeta
from mteb.types import Array, BatchedInput, PromptType

from .rerankers_custom import RerankerWrapper

logger = logging.getLogger(__name__)


# Based on https://github.com/castorini/pygaggle/blob/f54ae53d6183c1b66444fa5a0542301e0d1090f5/pygaggle/rerank/base.py#L63
prediction_tokens = {
    "castorini/monot5-small-msmarco-10k": ["▁false", "▁true"],
    "castorini/monot5-small-msmarco-100k": ["▁false", "▁true"],
    "castorini/monot5-base-msmarco": ["▁false", "▁true"],
    "castorini/monot5-base-msmarco-10k": ["▁false", "▁true"],
    "castorini/monot5-large-msmarco": ["▁false", "▁true"],
    "castorini/monot5-large-msmarco-10k": ["▁false", "▁true"],
    "castorini/monot5-base-med-msmarco": ["▁false", "▁true"],
    "castorini/monot5-3b-med-msmarco": ["▁false", "▁true"],
    "castorini/monot5-3b-msmarco-10k": ["▁false", "▁true"],
    "castorini/monot5-3b-msmarco": ["▁false", "▁true"],
    "unicamp-dl/mt5-base-en-msmarco": ["▁no", "▁yes"],
    "unicamp-dl/mt5-base-mmarco-v2": ["▁no", "▁yes"],
    "unicamp-dl/mt5-base-mmarco-v1": ["▁no", "▁yes"],
    "unicamp-dl/mt5-13b-mmarco-100k": ["▁", "▁true"],
}


def chunks(lst, n):
    for i in range(0, len(lst), n):
        yield lst[i : i + n]


class MonoT5Reranker(RerankerWrapper):
    name: str = "MonoT5"
    prompt_template: str = "Query: {query} Document: {text} Relevant:"

    def __init__(
        self,
        model_name_or_path="castorini/monot5-base-msmarco-10k",
        **kwargs,
    ):
        super().__init__(model_name_or_path, **kwargs)
        from transformers import (
            AutoModelForSeq2SeqLM,
            AutoTokenizer,
        )

        if not self.device:
            self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
        model_args = {}
        if self.fp_options:
            model_args["torch_dtype"] = self.fp_options
        self.model = AutoModelForSeq2SeqLM.from_pretrained(
            model_name_or_path, **model_args
        )
        logger.info(f"Using model {model_name_or_path}")

        if kwargs.get("torch_compile"):
            self.torch_compile = kwargs["torch_compile"]
            self.model = torch.compile(self.model)
        else:
            self.torch_compile = False

        self.model.to(self.device)
        self.tokenizer = AutoTokenizer.from_pretrained(model_name_or_path)
        self.token_false_id, self.token_true_id = self.get_prediction_tokens(
            model_name_or_path,
            self.tokenizer,
            kwargs["token_false"] if "token_false" in kwargs else None,
            kwargs["token_true"] if "token_true" in kwargs else None,
        )
        logger.info(f"Using max_length of {self.tokenizer.model_max_length}")
        logger.info(f"Using token_false_id of {self.token_false_id}")
        logger.info(f"Using token_true_id of {self.token_true_id}")
        self.max_length = min(
            2048, self.tokenizer.model_max_length
        )  # sometimes it's a v large number/max int
        logger.info(f"Using max_length of {self.max_length}")

        self.model.eval()

    def get_prediction_tokens(
        self, model_name_or_path, tokenizer, token_false=None, token_true=None
    ):
        if not (token_false and token_true):
            if model_name_or_path in prediction_tokens:
                token_false, token_true = prediction_tokens[model_name_or_path]
                token_false_id = tokenizer.get_vocab()[token_false]
                token_true_id = tokenizer.get_vocab()[token_true]
                return token_false_id, token_true_id
            else:
                raise Exception(
                    f"We don't know the indexes for the non-relevant/relevant tokens for\
                        the checkpoint {model_name_or_path} and you did not provide any."
                )
        else:
            token_false_id = tokenizer.get_vocab()[token_false]
            token_true_id = tokenizer.get_vocab()[token_true]
            return token_false_id, token_true_id

    @torch.inference_mode()
    def predict(
        self,
        inputs1: DataLoader[BatchedInput],
        inputs2: DataLoader[BatchedInput],
        *,
        task_metadata: TaskMetadata,
        hf_split: str,
        hf_subset: str,
        prompt_type: PromptType | None = None,
        **kwargs: Any,
    ) -> Array:
        queries = [text for batch in inputs1 for text in batch["query"]]
        instructions = None
        if "instruction" in inputs2.dataset.features:
            instructions = [text for batch in inputs1 for text in batch["instruction"]]
        passages = [text for batch in inputs2 for text in batch["text"]]

        if instructions is not None and instructions[0] is not None:
            queries = [f"{q} {i}".strip() for i, q in zip(instructions, queries)]

        prompts = [
            self.prompt_template.format(query=query, text=text)
            for (query, text) in zip(queries, passages)
        ]

        tokens = self.tokenizer(
            prompts,
            padding=True,
            truncation=True,
            return_tensors="pt",
            max_length=self.max_length,
            pad_to_multiple_of=(8 if self.torch_compile else None),
        ).to(self.device)
        output = self.model.generate(
            **tokens,
            max_new_tokens=1,
            return_dict_in_generate=True,
            output_scores=True,
        )
        batch_scores = output.scores[0]
        batch_scores = batch_scores[:, [self.token_false_id, self.token_true_id]]
        batch_scores = torch.nn.functional.log_softmax(batch_scores, dim=1)
        return batch_scores[:, 1].exp().tolist()


class LlamaReranker(RerankerWrapper):
    name: str = "LLAMA-Based"

    def __init__(
        self, model_name_or_path: str, is_classification: bool = False, **kwargs
    ):
        from transformers import AutoModelForCausalLM, AutoTokenizer

        kwargs.pop("torch_compile", None)
        super().__init__(model_name_or_path, **kwargs)

        if "chat" in model_name_or_path:
            self.template = """<s>[INST] <<SYS>>
You are an expert at finding information. Determine if the following document is relevant to the query (true/false).
<</SYS>>Query: {query}
Document: {text}
Relevant: [/INST]"""
        else:
            self.template = """Determine if the following document is relevant to the query (true/false).

Query: {query}
Document: {text}
Relevant: """

        self.query_instruct_template = "{query} {instruction}"
        logger.info(f"Using query_instruct_template of {self.query_instruct_template}")
        self.is_classification = is_classification

        model_args = {}
        if self.fp_options:
            model_args["torch_dtype"] = self.fp_options

        logger.info(self.template)
        logger.info(model_name_or_path)
        if not self.device:
            self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

        self.model = AutoModelForCausalLM.from_pretrained(
            model_name_or_path, **model_args
        )
        self.model.to(self.device)

        self.tokenizer = AutoTokenizer.from_pretrained(
            model_name_or_path, padding_side="left"
        )
        self.tokenizer.pad_token = self.tokenizer.eos_token
        self.tokenizer.padding_side = "left"

        self.token_false_id = self.tokenizer.get_vocab()["false"]
        self.token_true_id = self.tokenizer.get_vocab()["true"]
        self.max_length = min(2048, self.tokenizer.model_max_length)
        logger.info(f"Using max_length of {self.max_length}")
        self.gpu_count = torch.cuda.device_count()
        if self.gpu_count > 1:
            logger.info(f"Using {self.gpu_count} GPUs")
            self.model = torch.nn.DataParallel(self.model)
        self.model.eval()

    @torch.inference_mode()
    def predict(
        self,
        inputs1: DataLoader[BatchedInput],
        inputs2: DataLoader[BatchedInput],
        *,
        task_metadata: TaskMetadata,
        hf_split: str,
        hf_subset: str,
        prompt_type: PromptType | None = None,
        **kwargs: Any,
    ) -> Array:
        queries = [text for batch in inputs1 for text in batch["query"]]
        instructions = None
        if "instruction" in inputs2.dataset.features:
            instructions = [text for batch in inputs1 for text in batch["instruction"]]
        passages = [text for batch in inputs2 for text in batch["text"]]

        if instructions is not None and instructions[0] is not None:
            # logger.info(f"Adding instructions to LLAMA queries")
            queries = [
                self.query_instruct_template.format(instruction=i, query=q).strip()
                for i, q in zip(instructions, queries)
            ]

        prompts = [
            self.template.format(query=query, text=text)
            for (query, text) in zip(queries, passages)
        ]
        assert "{query}" not in prompts[0], "Query not replaced"
        assert "{text}" not in prompts[0], "Text not replaced"
        assert "{instruction}" not in prompts[0], "Instruction not replaced"

        tokens = self.tokenizer(
            prompts,
            padding=True,
            truncation=True,
            return_tensors="pt",
            max_length=self.max_length,
            pad_to_multiple_of=None,
        ).to(self.device)
        if "token_type_ids" in tokens:
            del tokens["token_type_ids"]
        if not self.is_classification:
            batch_scores = self.model(**tokens).logits[:, -1, :]
            true_vector = batch_scores[:, self.token_true_id]
            false_vector = batch_scores[:, self.token_false_id]
            batch_scores = torch.stack([false_vector, true_vector], dim=1)
            batch_scores = torch.nn.functional.log_softmax(batch_scores, dim=1)
            scores = batch_scores[:, 1].exp().tolist()
        else:
            batch_scores = self.model(**tokens).logits
            batch_scores = torch.nn.functional.log_softmax(batch_scores, dim=1)
            scores = batch_scores[:, 1].exp().tolist()

        return scores


class MistralReranker(LlamaReranker):
    name: str = "Mistral"

    def __init__(self, model_name_or_path: str, **kwargs):
        # use the base class for everything except template
        super().__init__(model_name_or_path, **kwargs)
        self.template = """<s>[INST] You are an expert Google searcher, whose job is to determine if the following document is relevant to the query (true/false).
Query: {query}
Document: {text}
Relevant (either "true" or "false"): [/INST]"""
        self.max_length = min(2048, self.tokenizer.model_max_length)
        logger.info(f"Using max_length of {self.max_length}")
        logger.info(f"Using template of {self.template}")


class FollowIRReranker(LlamaReranker):
    name: str = "FollowIR"

    def __init__(self, model_name_or_path: str, **kwargs):
        # use the base class for everything except template
        super().__init__(model_name_or_path, **kwargs)
        self.template = """<s> [INST] You are an expert Google searcher, whose job is to determine if the following document is relevant to the query (true/false). Answer using only one word, one of those two choices.

Query: {query}
Document: {text}
Relevant (only output one word, either "true" or "false"): [/INST] """
        self.max_length = min(2048, self.tokenizer.model_max_length)
        logger.info(f"Using template of {self.template}")


class FLANT5Reranker(MonoT5Reranker):
    name: str = "FLAN-T5"
    prompt_template: str = """Is the following passage relevant to the query?
Query: {query}
Passage: {text}"""

    def get_prediction_tokens(self, *args, **kwargs):
        yes_token_id, *_ = self.tokenizer.encode("yes")
        no_token_id, *_ = self.tokenizer.encode("no")
        return no_token_id, yes_token_id


monot5_small = ModelMeta(
    loader=MonoT5Reranker,
    loader_kwargs=dict(
        fp_options="float16",
    ),
    name="castorini/monot5-small-msmarco-10k",
    languages=["eng-Latn"],
    open_weights=True,
    revision="77f8e3f7b1eb1afe353aa21a7c3a2fc8feca702e",
    release_date="2022-03-28",
    n_parameters=None,
    memory_usage_mb=None,
    max_tokens=None,
    embed_dim=None,
    license=None,
    public_training_code=None,
    public_training_data=None,
    similarity_fn_name=None,
    use_instructions=None,
    training_datasets=None,
    framework=["PyTorch"],
    is_cross_encoder=True,
    citation="""@misc{rosa2022parameterleftbehinddistillation,
      title={No Parameter Left Behind: How Distillation and Model Size Affect Zero-Shot Retrieval},
      author={Guilherme Moraes Rosa and Luiz Bonifacio and Vitor Jeronymo and Hugo Abonizio and Marzieh Fadaee and Roberto Lotufo and Rodrigo Nogueira},
      year={2022},
      eprint={2206.02873},
      archivePrefix={arXiv},
      primaryClass={cs.IR},
      url={https://arxiv.org/abs/2206.02873},
    }""",
)

monot5_base = ModelMeta(
    loader=MonoT5Reranker,  # type: ignore
    loader_kwargs=dict(
        fp_options="float16",
    ),
    name="castorini/monot5-base-msmarco-10k",
    languages=["eng-Latn"],
    open_weights=True,
    revision="f15657ab3d2a5dd0b9a30c8c0b6a0a73c9cb5884",
    release_date="2022-03-28",
    citation="""@misc{rosa2022parameterleftbehinddistillation,
      title={No Parameter Left Behind: How Distillation and Model Size Affect Zero-Shot Retrieval},
      author={Guilherme Moraes Rosa and Luiz Bonifacio and Vitor Jeronymo and Hugo Abonizio and Marzieh Fadaee and Roberto Lotufo and Rodrigo Nogueira},
      year={2022},
      eprint={2206.02873},
      archivePrefix={arXiv},
      primaryClass={cs.IR},
      url={https://arxiv.org/abs/2206.02873},
    }""",
    n_parameters=None,
    memory_usage_mb=None,
    max_tokens=None,
    embed_dim=None,
    license=None,
    public_training_code=None,
    public_training_data=None,
    similarity_fn_name=None,
    use_instructions=None,
    training_datasets=None,
    framework=["PyTorch"],
    is_cross_encoder=True,
)

monot5_large = ModelMeta(
    loader=MonoT5Reranker,
    loader_kwargs=dict(
        fp_options="float16",
    ),
    name="castorini/monot5-large-msmarco-10k",
    languages=["eng-Latn"],
    open_weights=True,
    revision="48cfad1d8dd587670393f27ee8ec41fde63e3d98",
    release_date="2022-03-28",
    n_parameters=None,
    memory_usage_mb=None,
    max_tokens=None,
    embed_dim=None,
    license=None,
    public_training_code=None,
    public_training_data=None,
    similarity_fn_name=None,
    use_instructions=None,
    training_datasets=None,
    framework=["PyTorch"],
    is_cross_encoder=True,
    citation="""@misc{rosa2022parameterleftbehinddistillation,
      title={No Parameter Left Behind: How Distillation and Model Size Affect Zero-Shot Retrieval},
      author={Guilherme Moraes Rosa and Luiz Bonifacio and Vitor Jeronymo and Hugo Abonizio and Marzieh Fadaee and Roberto Lotufo and Rodrigo Nogueira},
      year={2022},
      eprint={2206.02873},
      archivePrefix={arXiv},
      primaryClass={cs.IR},
      url={https://arxiv.org/abs/2206.02873},
    }""",
)

monot5_3b = ModelMeta(
    loader=MonoT5Reranker,
    loader_kwargs=dict(
        fp_options="float16",
    ),
    name="castorini/monot5-3b-msmarco-10k",
    languages=["eng-Latn"],
    open_weights=True,
    revision="bc0c419a438c81f592f878ce32430a1823f5db6c",
    release_date="2022-03-28",
    n_parameters=None,
    memory_usage_mb=None,
    max_tokens=None,
    embed_dim=None,
    license=None,
    public_training_code=None,
    public_training_data=None,
    similarity_fn_name=None,
    use_instructions=None,
    training_datasets=None,
    framework=["PyTorch"],
    is_cross_encoder=True,
    citation="""@misc{rosa2022parameterleftbehinddistillation,
      title={No Parameter Left Behind: How Distillation and Model Size Affect Zero-Shot Retrieval},
      author={Guilherme Moraes Rosa and Luiz Bonifacio and Vitor Jeronymo and Hugo Abonizio and Marzieh Fadaee and Roberto Lotufo and Rodrigo Nogueira},
      year={2022},
      eprint={2206.02873},
      archivePrefix={arXiv},
      primaryClass={cs.IR},
      url={https://arxiv.org/abs/2206.02873},
    }""",
)

flant5_base = ModelMeta(
    loader=FLANT5Reranker,  # type: ignore
    loader_kwargs=dict(
        fp_options="float16",
    ),
    name="google/flan-t5-base",
    languages=["eng-Latn"],
    open_weights=True,
    revision="7bcac572ce56db69c1ea7c8af255c5d7c9672fc2",
    release_date="2022-10-21",
    citation="""@misc{10.48550/arxiv.2210.11416,
      doi = {10.48550/ARXIV.2210.11416},
      url = {https://arxiv.org/abs/2210.11416},
      author = {Chung, Hyung Won and Hou, Le and Longpre, Shayne and Zoph, Barret and Tay, Yi and Fedus, William and Li, Eric and Wang, Xuezhi and Dehghani, Mostafa and Brahma, Siddhartha and Webson, Albert and Gu, Shixiang Shane and Dai, Zhuyun and Suzgun, Mirac and Chen, Xinyun and Chowdhery, Aakanksha and Narang, Sharan and Mishra, Gaurav and Yu, Adams and Zhao, Vincent and Huang, Yanping and Dai, Andrew and Yu, Hongkun and Petrov, Slav and Chi, Ed H. and Dean, Jeff and Devlin, Jacob and Roberts, Adam and Zhou, Denny and Le, Quoc V. and Wei, Jason},
      keywords = {Machine Learning (cs.LG), Computation and Language (cs.CL), FOS: Computer and information sciences, FOS: Computer and information sciences},
      title = {Scaling Instruction-Finetuned Language Models},
      publisher = {arXiv},
      year = {2022},
      copyright = {Creative Commons Attribution 4.0 International}
    }
    """,
    training_datasets=set(
        # "svakulenk0/qrecc": ["train"],
        # "taskmaster2": ["train"],
        # "djaym7/wiki_dialog": ["train"],
        # "deepmind/code_contests": ["train"],
        # "lambada": ["train"],
        # "gsm8k": ["train"],
        # "aqua_rat": ["train"],
        # "esnli": ["train"],
        # "quasc": ["train"],
        # "qed": ["train"],
    ),
    n_parameters=None,
    memory_usage_mb=944,
    max_tokens=None,
    embed_dim=None,
    license=None,
    public_training_code=None,
    public_training_data=None,
    similarity_fn_name=None,
    use_instructions=None,
    framework=["PyTorch"],
    is_cross_encoder=True,
)

flant5_large = ModelMeta(
    loader=FLANT5Reranker,
    loader_kwargs=dict(
        fp_options="float16",
    ),
    name="google/flan-t5-large",
    languages=["eng-Latn"],
    open_weights=True,
    revision="0613663d0d48ea86ba8cb3d7a44f0f65dc596a2a",
    release_date="2022-10-21",
    citation="""@misc{10.48550/arxiv.2210.11416,
      doi = {10.48550/ARXIV.2210.11416},
      url = {https://arxiv.org/abs/2210.11416},
      author = {Chung, Hyung Won and Hou, Le and Longpre, Shayne and Zoph, Barret and Tay, Yi and Fedus, William and Li, Eric and Wang, Xuezhi and Dehghani, Mostafa and Brahma, Siddhartha and Webson, Albert and Gu, Shixiang Shane and Dai, Zhuyun and Suzgun, Mirac and Chen, Xinyun and Chowdhery, Aakanksha and Narang, Sharan and Mishra, Gaurav and Yu, Adams and Zhao, Vincent and Huang, Yanping and Dai, Andrew and Yu, Hongkun and Petrov, Slav and Chi, Ed H. and Dean, Jeff and Devlin, Jacob and Roberts, Adam and Zhou, Denny and Le, Quoc V. and Wei, Jason},
      keywords = {Machine Learning (cs.LG), Computation and Language (cs.CL), FOS: Computer and information sciences, FOS: Computer and information sciences},
      title = {Scaling Instruction-Finetuned Language Models},
      publisher = {arXiv},
      year = {2022},
      copyright = {Creative Commons Attribution 4.0 International}
    }
    """,
    training_datasets=set(
        # "svakulenk0/qrecc": ["train"],
        # "taskmaster2": ["train"],
        # "djaym7/wiki_dialog": ["train"],
        # "deepmind/code_contests": ["train"],
        # "lambada": ["train"],
        # "gsm8k": ["train"],
        # "aqua_rat": ["train"],
        # "esnli": ["train"],
        # "quasc": ["train"],
        # "qed": ["train"],
    ),
    n_parameters=None,
    memory_usage_mb=2987,
    max_tokens=None,
    embed_dim=None,
    license=None,
    public_training_code=None,
    public_training_data=None,
    similarity_fn_name=None,
    use_instructions=None,
    framework=["PyTorch"],
    is_cross_encoder=True,
)

flant5_xl = ModelMeta(
    loader=FLANT5Reranker,
    loader_kwargs=dict(
        fp_options="float16",
    ),
    name="google/flan-t5-xl",
    languages=["eng-Latn"],
    open_weights=True,
    revision="7d6315df2c2fb742f0f5b556879d730926ca9001",
    release_date="2022-10-21",
    citation="""@misc{10.48550/arxiv.2210.11416,
      doi = {10.48550/ARXIV.2210.11416},
      url = {https://arxiv.org/abs/2210.11416},
      author = {Chung, Hyung Won and Hou, Le and Longpre, Shayne and Zoph, Barret and Tay, Yi and Fedus, William and Li, Eric and Wang, Xuezhi and Dehghani, Mostafa and Brahma, Siddhartha and Webson, Albert and Gu, Shixiang Shane and Dai, Zhuyun and Suzgun, Mirac and Chen, Xinyun and Chowdhery, Aakanksha and Narang, Sharan and Mishra, Gaurav and Yu, Adams and Zhao, Vincent and Huang, Yanping and Dai, Andrew and Yu, Hongkun and Petrov, Slav and Chi, Ed H. and Dean, Jeff and Devlin, Jacob and Roberts, Adam and Zhou, Denny and Le, Quoc V. and Wei, Jason},
      keywords = {Machine Learning (cs.LG), Computation and Language (cs.CL), FOS: Computer and information sciences, FOS: Computer and information sciences},
      title = {Scaling Instruction-Finetuned Language Models},
      publisher = {arXiv},
      year = {2022},
      copyright = {Creative Commons Attribution 4.0 International}
    }
    """,
    training_datasets=set(
        # "svakulenk0/qrecc": ["train"],
        # "taskmaster2": ["train"],
        # "djaym7/wiki_dialog": ["train"],
        # "deepmind/code_contests": ["train"],
        # "lambada": ["train"],
        # "gsm8k": ["train"],
        # "aqua_rat": ["train"],
        # "esnli": ["train"],
        # "quasc": ["train"],
        # "qed": ["train"],
    ),
    n_parameters=None,
    memory_usage_mb=10871,
    max_tokens=None,
    embed_dim=None,
    license=None,
    public_training_code=None,
    public_training_data=None,
    similarity_fn_name=None,
    use_instructions=None,
    framework=["PyTorch"],
    is_cross_encoder=True,
)

flant5_xxl = ModelMeta(
    loader=FLANT5Reranker,
    loader_kwargs=dict(
        fp_options="float16",
    ),
    name="google/flan-t5-xxl",
    languages=["eng-Latn"],
    open_weights=True,
    revision="ae7c9136adc7555eeccc78cdd960dfd60fb346ce",
    release_date="2022-10-21",
    citation="""@misc{10.48550/arxiv.2210.11416,
      doi = {10.48550/ARXIV.2210.11416},
      url = {https://arxiv.org/abs/2210.11416},
      author = {Chung, Hyung Won and Hou, Le and Longpre, Shayne and Zoph, Barret and Tay, Yi and Fedus, William and Li, Eric and Wang, Xuezhi and Dehghani, Mostafa and Brahma, Siddhartha and Webson, Albert and Gu, Shixiang Shane and Dai, Zhuyun and Suzgun, Mirac and Chen, Xinyun and Chowdhery, Aakanksha and Narang, Sharan and Mishra, Gaurav and Yu, Adams and Zhao, Vincent and Huang, Yanping and Dai, Andrew and Yu, Hongkun and Petrov, Slav and Chi, Ed H. and Dean, Jeff and Devlin, Jacob and Roberts, Adam and Zhou, Denny and Le, Quoc V. and Wei, Jason},
      keywords = {Machine Learning (cs.LG), Computation and Language (cs.CL), FOS: Computer and information sciences, FOS: Computer and information sciences},
      title = {Scaling Instruction-Finetuned Language Models},
      publisher = {arXiv},
      year = {2022},
      copyright = {Creative Commons Attribution 4.0 International}
    }
    """,
    training_datasets=set(
        # "svakulenk0/qrecc": ["train"],
        # "taskmaster2": ["train"],
        # "djaym7/wiki_dialog": ["train"],
        # "deepmind/code_contests": ["train"],
        # "lambada": ["train"],
        # "gsm8k": ["train"],
        # "aqua_rat": ["train"],
        # "esnli": ["train"],
        # "quasc": ["train"],
        # "qed": ["train"],
    ),
    n_parameters=None,
    memory_usage_mb=42980,
    max_tokens=None,
    embed_dim=None,
    license=None,
    public_training_code=None,
    public_training_data=None,
    similarity_fn_name=None,
    use_instructions=None,
    framework=["PyTorch"],
    is_cross_encoder=True,
)


llama2_7b = ModelMeta(
    loader=LlamaReranker,
    loader_kwargs=dict(
        fp_options="float16",
    ),
    name="meta-llama/Llama-2-7b-hf",
    languages=["eng-Latn"],
    open_weights=True,
    revision="01c7f73d771dfac7d292323805ebc428287df4f9",
    release_date="2023-07-18",
    n_parameters=None,
    memory_usage_mb=None,
    max_tokens=None,
    embed_dim=None,
    license=None,
    public_training_code=None,
    public_training_data=None,
    similarity_fn_name=None,
    use_instructions=None,
    training_datasets=None,
    framework=["PyTorch"],
    citation="""@misc{touvron2023llama2openfoundation,
      title={Llama 2: Open Foundation and Fine-Tuned Chat Models},
      author={Hugo Touvron and Louis Martin and Kevin Stone and Peter Albert and Amjad Almahairi and Yasmine Babaei and Nikolay Bashlykov and Soumya Batra and Prajjwal Bhargava and Shruti Bhosale and Dan Bikel and Lukas Blecher and Cristian Canton Ferrer and Moya Chen and Guillem Cucurull and David Esiobu and Jude Fernandes and Jeremy Fu and Wenyin Fu and Brian Fuller and Cynthia Gao and Vedanuj Goswami and Naman Goyal and Anthony Hartshorn and Saghar Hosseini and Rui Hou and Hakan Inan and Marcin Kardas and Viktor Kerkez and Madian Khabsa and Isabel Kloumann and Artem Korenev and Punit Singh Koura and Marie-Anne Lachaux and Thibaut Lavril and Jenya Lee and Diana Liskovich and Yinghai Lu and Yuning Mao and Xavier Martinet and Todor Mihaylov and Pushkar Mishra and Igor Molybog and Yixin Nie and Andrew Poulton and Jeremy Reizenstein and Rashi Rungta and Kalyan Saladi and Alan Schelten and Ruan Silva and Eric Michael Smith and Ranjan Subramanian and Xiaoqing Ellen Tan and Binh Tang and Ross Taylor and Adina Williams and Jian Xiang Kuan and Puxin Xu and Zheng Yan and Iliyan Zarov and Yuchen Zhang and Angela Fan and Melanie Kambadur and Sharan Narang and Aurelien Rodriguez and Robert Stojnic and Sergey Edunov and Thomas Scialom},
      year={2023},
      eprint={2307.09288},
      archivePrefix={arXiv},
      primaryClass={cs.CL},
      url={https://arxiv.org/abs/2307.09288},
    }""",
    is_cross_encoder=True,
)

llama2_7b_chat = ModelMeta(
    loader=LlamaReranker,
    loader_kwargs=dict(
        fp_options="float16",
    ),
    name="meta-llama/Llama-2-7b-chat-hf",
    languages=["eng-Latn"],
    open_weights=True,
    revision="f5db02db724555f92da89c216ac04704f23d4590",
    release_date="2023-07-18",
    citation="""@misc{touvron2023llama2openfoundation,
      title={Llama 2: Open Foundation and Fine-Tuned Chat Models},
      author={Hugo Touvron and Louis Martin and Kevin Stone and Peter Albert and Amjad Almahairi and Yasmine Babaei and Nikolay Bashlykov and Soumya Batra and Prajjwal Bhargava and Shruti Bhosale and Dan Bikel and Lukas Blecher and Cristian Canton Ferrer and Moya Chen and Guillem Cucurull and David Esiobu and Jude Fernandes and Jeremy Fu and Wenyin Fu and Brian Fuller and Cynthia Gao and Vedanuj Goswami and Naman Goyal and Anthony Hartshorn and Saghar Hosseini and Rui Hou and Hakan Inan and Marcin Kardas and Viktor Kerkez and Madian Khabsa and Isabel Kloumann and Artem Korenev and Punit Singh Koura and Marie-Anne Lachaux and Thibaut Lavril and Jenya Lee and Diana Liskovich and Yinghai Lu and Yuning Mao and Xavier Martinet and Todor Mihaylov and Pushkar Mishra and Igor Molybog and Yixin Nie and Andrew Poulton and Jeremy Reizenstein and Rashi Rungta and Kalyan Saladi and Alan Schelten and Ruan Silva and Eric Michael Smith and Ranjan Subramanian and Xiaoqing Ellen Tan and Binh Tang and Ross Taylor and Adina Williams and Jian Xiang Kuan and Puxin Xu and Zheng Yan and Iliyan Zarov and Yuchen Zhang and Angela Fan and Melanie Kambadur and Sharan Narang and Aurelien Rodriguez and Robert Stojnic and Sergey Edunov and Thomas Scialom},
      year={2023},
      eprint={2307.09288},
      archivePrefix={arXiv},
      primaryClass={cs.CL},
      url={https://arxiv.org/abs/2307.09288},
    }""",
    n_parameters=None,
    memory_usage_mb=None,
    max_tokens=None,
    embed_dim=None,
    license=None,
    public_training_code=None,
    public_training_data=None,
    similarity_fn_name=None,
    use_instructions=None,
    training_datasets=None,
    framework=["PyTorch"],
    is_cross_encoder=True,
)

mistral_7b = ModelMeta(
    loader=MistralReranker,
    loader_kwargs=dict(
        fp_options="float16",
    ),
    name="mistralai/Mistral-7B-Instruct-v0.2",
    languages=["eng-Latn"],
    open_weights=True,
    revision="3ad372fc79158a2148299e3318516c786aeded6c",
    release_date="2023-12-11",
    n_parameters=None,
    memory_usage_mb=None,
    max_tokens=None,
    embed_dim=None,
    license=None,
    public_training_code=None,
    public_training_data=None,
    similarity_fn_name=None,
    use_instructions=None,
    training_datasets=None,
    framework=["PyTorch"],
    citation="""@misc{jiang2023mistral7b,
      title={Mistral 7B},
      author={Albert Q. Jiang and Alexandre Sablayrolles and Arthur Mensch and Chris Bamford and Devendra Singh Chaplot and Diego de las Casas and Florian Bressand and Gianna Lengyel and Guillaume Lample and Lucile Saulnier and Lélio Renard Lavaud and Marie-Anne Lachaux and Pierre Stock and Teven Le Scao and Thibaut Lavril and Thomas Wang and Timothée Lacroix and William El Sayed},
      year={2023},
      eprint={2310.06825},
      archivePrefix={arXiv},
      primaryClass={cs.CL},
      url={https://arxiv.org/abs/2310.06825},
    }""",
    is_cross_encoder=True,
)

followir_7b = ModelMeta(
    loader=FollowIRReranker,
    loader_kwargs=dict(
        fp_options="float16",
    ),
    name="jhu-clsp/FollowIR-7B",
    languages=["eng-Latn"],
    open_weights=True,
    revision="4d25d437e38b510c01852070c0731e8f6e1875d1",
    release_date="2024-04-29",
    training_datasets=set(
        # "jhu-clsp/FollowIR-train"
    ),
    n_parameters=None,
    memory_usage_mb=13813,
    max_tokens=None,
    embed_dim=None,
    license=None,
    public_training_code=None,
    public_training_data=None,
    similarity_fn_name=None,
    use_instructions=None,
    framework=["PyTorch"],
    citation="""
    @misc{weller2024followir,
      title={FollowIR: Evaluating and Teaching Information Retrieval Models to Follow Instructions},
      author={Orion Weller and Benjamin Chang and Sean MacAvaney and Kyle Lo and Arman Cohan and Benjamin Van Durme and Dawn Lawrie and Luca Soldaini},
      year={2024},
      eprint={2403.15246},
      archivePrefix={arXiv},
      primaryClass={cs.IR}
    }
    """,
    is_cross_encoder=True,
)


mt5_languages = [
    "afr-Latn",
    "sqi-Latn",
    "amh-Ethi",
    "ara-Arab",
    "hye-Armn",
    "aze-Latn",
    "eus-Latn",
    "bel-Cyrl",
    "ben-Beng",
    "bul-Cyrl",
    "mya-Mymr",
    "cat-Latn",
    "ceb-Latn",
    "nya-Latn",
    "zho-Hans",
    "cos-Latn",
    "ces-Latn",
    "dan-Latn",
    "nld-Latn",
    "eng-Latn",
    "epo-Latn",
    "est-Latn",
    "fil-Latn",
    "fin-Latn",
    "fra-Latn",
    "glg-Latn",
    "kat-Geor",
    "deu-Latn",
    "ell-Grek",
    "guj-Gujr",
    "hat-Latn",
    "hau-Latn",
    "haw-Latn",
    "heb-Hebr",
    "hin-Deva",
    "hmn-Latn",
    "hun-Latn",
    "isl-Latn",
    "ibo-Latn",
    "ind-Latn",
    "gle-Latn",
    "ita-Latn",
    "jpn-Jpan",
    "jav-Latn",
    "kan-Knda",
    "kaz-Cyrl",
    "khm-Khmr",
    "kor-Hang",
    "kur-Latn",
    "kir-Cyrl",
    "lao-Laoo",
    "lat-Latn",
    "lav-Latn",
    "lit-Latn",
    "ltz-Latn",
    "mkd-Cyrl",
    "mlg-Latn",
    "msa-Latn",
    "mal-Mlym",
    "mlt-Latn",
    "mri-Latn",
    "mar-Deva",
    "mon-Cyrl",
    "nep-Deva",
    "nor-Latn",
    "nno-Latn",
    "nob-Latn",
    "pus-Arab",
    "fas-Arab",
    "pol-Latn",
    "por-Latn",
    "pan-Guru",
    "ron-Latn",
    "rus-Cyrl",
    "smo-Latn",
    "gla-Latn",
    "srp-Cyrl",
    "sna-Latn",
    "snd-Arab",
    "sin-Sinh",
    "slk-Latn",
    "slv-Latn",
    "som-Latn",
    "sot-Latn",
    "spa-Latn",
    "sun-Latn",
    "swa-Latn",
    "swe-Latn",
    "tgk-Cyrl",
    "tam-Taml",
    "tel-Telu",
    "tha-Thai",
    "tur-Latn",
    "ukr-Cyrl",
    "urd-Arab",
    "uzb-Latn",
    "vie-Latn",
    "cym-Latn",
    "fry-Latn",
    "xho-Latn",
    "yid-Hebr",
    "yor-Latn",
    "zul-Latn",
]

mt5_base_mmarco_v2 = ModelMeta(
    loader=MonoT5Reranker,
    loader_kwargs=dict(
        fp_options="float16",
    ),
    name="unicamp-dl/mt5-base-mmarco-v2",
    languages=mt5_languages,
    open_weights=True,
    revision="cc0a949b9f21efcaba45c8cabb998ad02ce8d4e7",
    release_date="2022-01-05",
    citation="""@misc{bonifacio2021mmarco,
      title={mMARCO: A Multilingual Version of MS MARCO Passage Ranking Dataset},
      author={Luiz Henrique Bonifacio and Vitor Jeronymo and Hugo Queiroz Abonizio and Israel Campiotti and Marzieh Fadaee and  and Roberto Lotufo and Rodrigo Nogueira},
      year={2021},
      eprint={2108.13897},
      archivePrefix={arXiv},
      primaryClass={cs.CL}
    }
    """,
    training_datasets={"MSMARCO"},
    n_parameters=None,
    memory_usage_mb=None,
    max_tokens=None,
    embed_dim=None,
    license=None,
    public_training_code=None,
    public_training_data=None,
    similarity_fn_name=None,
    use_instructions=None,
    framework=["PyTorch"],
    is_cross_encoder=True,
)

mt5_13b_mmarco_100k = ModelMeta(
    loader=MonoT5Reranker,  # type: ignore
    loader_kwargs=dict(
        fp_options="float16",
    ),
    name="unicamp-dl/mt5-13b-mmarco-100k",
    languages=mt5_languages,
    open_weights=True,
    revision="e1a4317e102a525ea9e16745ad21394a4f1bffbc",
    release_date="2022-11-04",
    n_parameters=None,
    memory_usage_mb=None,
    max_tokens=None,
    embed_dim=None,
    license=None,
    public_training_code=None,
    public_training_data=None,
    similarity_fn_name=None,
    use_instructions=None,
    training_datasets=None,
    framework=["PyTorch"],
    is_cross_encoder=True,
)
