GraphRAG-Benchmark icon indicating copy to clipboard operation
GraphRAG-Benchmark copied to clipboard

HippoRAG2 NotImplementedError

Open xiaotao44 opened this issue 1 year ago • 1 comments

hello~最近在复现这边hipporag2的benchmark部分,hipporag2是根据 https://github.com/OSU-NLP-Group/HippoRAG 直接安装的:pip install hipporag,发现除了您提到的适配部分,BGE.py需要额外补充batch_encode的实现,否则会在父类BaseEmbeddingModel处报错NotImplementedError,以下是让gpt写的,已测试可以跑通

def batch_encode(self, texts: List[str], **kwargs) -> np.ndarray:
        """
        Batch encode texts using BGE model with progress bar support.
        
        Args:
            texts: List of texts to encode
            **kwargs: Additional parameters (batch_size, instruction, etc.)
            
        Returns:
            numpy.ndarray: Encoded embeddings
        """
        if isinstance(texts, str):
            texts = [texts]

        params = deepcopy(self.embedding_config.encode_params)
        if kwargs:
            params.update(kwargs)

        batch_size = params.pop("batch_size", self.global_config.embedding_batch_size)
        instruction = params.pop("instruction", "")
        max_length = params.get("max_length", self.embedding_config.encode_params["max_length"])

        logger.debug(f"Calling {self.__class__.__name__} batch_encode with batch_size: {batch_size}")

        # Apply instruction if provided
        if instruction:
            texts = [f"{instruction}{text}" for text in texts]

        # Process in batches with progress bar
        if len(texts) <= batch_size:
            # Single batch
            encoded_input = self.tokenizer(
                texts,
                padding=True,
                truncation=True,
                max_length=max_length,
                return_tensors='pt'
            )
            
            with torch.no_grad():
                model_output = self.embedding_model(**encoded_input)
                sentence_embeddings = mean_pooling(model_output.last_hidden_state, encoded_input['attention_mask'])
                
            if self.embedding_config.norm:
                sentence_embeddings = torch.nn.functional.normalize(sentence_embeddings, p=2, dim=1)
                
            results = sentence_embeddings.cpu().numpy()
        else:
            # Multiple batches with progress bar
            pbar = tqdm(total=len(texts), desc="Batch Encoding")
            results = []
            
            for i in range(0, len(texts), batch_size):
                batch_texts = texts[i:i + batch_size]
                
                encoded_input = self.tokenizer(
                    batch_texts,
                    padding=True,
                    truncation=True,
                    max_length=max_length,
                    return_tensors='pt'
                )
                
                with torch.no_grad():
                    model_output = self.embedding_model(**encoded_input)
                    sentence_embeddings = mean_pooling(model_output.last_hidden_state, encoded_input['attention_mask'])
                    
                if self.embedding_config.norm:
                    sentence_embeddings = torch.nn.functional.normalize(sentence_embeddings, p=2, dim=1)
                    
                results.append(sentence_embeddings.cpu())
                pbar.update(len(batch_texts))
            
            pbar.close()
            results = torch.cat(results, dim=0).numpy()

        return results

xiaotao44 avatar Nov 29 '25 06:11 xiaotao44

您好,感谢您的关注,可能是因为hipporag2的相关仓库更新了内容,或者有些包版本不一致的问题导致了错误,很感谢您指出问题,您可以将相关代码pull requests,我们会将其合并,再次感谢

Eric-Xiang-526 avatar Nov 30 '25 02:11 Eric-Xiang-526