|
|

楼主 |
发表于 2026-9-12 23:46:25
|
显示全部楼层
- # -*- coding: utf-8 -*-
- """
- Spyder Editor
- This is a temporary script file.
- """
- from transformers import AutoTokenizer, AutoModel, AutoConfig
- import torch
- # Sentences we want sentence embeddings for
- sentences = ["RAG模型已初始化"]
- model_dir = r'D:/2-LearningCode/913_LM\RAG_WITIAI/bge-small-zh-1.5'
- # Load model from HuggingFace Hub
- tokenizer = AutoTokenizer.from_pretrained(model_dir)
- # model = AutoModel.from_pretrained('BAAI/bge-large-zh-v1.5')
- config = AutoConfig.from_pretrained(model_dir)
- model = AutoModel.from_config(config)
- model.eval()
- # torch.save(model.state_dict(), 'rag_'+ str(512) + '.pt')
- # model.load_state_dict(torch.load('rag_'+ str(512) + '.pt', map_location=torch.device('cpu') ))
- # model.eval()
- example1 = torch.randint(low=0, high=1000, size=(1, 512), dtype=torch.long).type(torch.LongTensor)
- example2 = torch.ones(1, 512).type(torch.LongTensor)
- example3 = torch.zeros(1, 512).type(torch.LongTensor)
- pt_model = torch.jit.trace(model, (example1,example2,example3), strict=False )
- pt_model.save( 'ragX_'+ str(512) + '.pt' )
- # 第二步,直接load,C++中是这样加载
- # model = torch.jit.load('ragX_'+ str(512) + '.pt')
- # model.eval()
- # Tokenize sentences
- # encoded_input = tokenizer(sentences, padding=True, truncation=True, return_tensors='pt')
- # for s2p(short query to long passage) retrieval task, add an instruction to query (not add instruction for passages)
- # encoded_input = tokenizer([instruction + q for q in queries], padding=True, truncation=True, return_tensors='pt')
- encoded_input = tokenizer(sentences)
- # Compute token embeddings
- with torch.no_grad():
- # model_output = model(**encoded_input)
- model_output = model( input_ids=torch.tensor(encoded_input['input_ids']),
- attention_mask=torch.tensor(encoded_input['attention_mask']),
- token_type_ids=torch.tensor(encoded_input['token_type_ids']) )
- # Perform pooling. In this case, cls pooling.
- sentence_embeddings = model_output[0][:, 0]
- # normalize embeddings
- sentence_embeddings = torch.nn.functional.normalize(sentence_embeddings, p=2, dim=1)
- print("Sentence embeddings:", sentence_embeddings)
复制代码 |
|