Hello Mat

 找回密码
 立即注册
查看: 1698|回复: 4

RAG知识检索

[复制链接]

1371

主题

1613

帖子

10

金钱

管理员

Rank: 9Rank: 9Rank: 9

积分
22905
发表于 2026-2-13 21:45:55 | 显示全部楼层 |阅读模式
RAG知识检索:
BAAI/bge-small-zh-v1.5 · HF Mirror

  1. from transformers import AutoTokenizer, AutoModel
  2. import torch
  3. # Sentences we want sentence embeddings for
  4. sentences = ["样例数据-1", "样例数据-2"]

  5. # Load model from HuggingFace Hub
  6. tokenizer = AutoTokenizer.from_pretrained('BAAI/bge-large-zh-v1.5')
  7. model = AutoModel.from_pretrained('BAAI/bge-large-zh-v1.5')
  8. model.eval()

  9. # Tokenize sentences
  10. encoded_input = tokenizer(sentences, padding=True, truncation=True, return_tensors='pt')
  11. # for s2p(short query to long passage) retrieval task, add an instruction to query (not add instruction for passages)
  12. # encoded_input = tokenizer([instruction + q for q in queries], padding=True, truncation=True, return_tensors='pt')

  13. # Compute token embeddings
  14. with torch.no_grad():
  15.     model_output = model(**encoded_input)
  16.     # Perform pooling. In this case, cls pooling.
  17.     sentence_embeddings = model_output[0][:, 0]
  18. # normalize embeddings
  19. sentence_embeddings = torch.nn.functional.normalize(sentence_embeddings, p=2, dim=1)
  20. print("Sentence embeddings:", sentence_embeddings)
复制代码


**encoded_input是三个tensor组合的。可以展开:类似这种model_output = model(tensor(encoded_input["input_ids"]), tensor(encoded_input["mask"]), tensor(encoded_input["ids"]))





算法QQ  3283892722
群智能算法链接http://halcom.cn/forum.php?mod=forumdisplay&fid=73
回复

使用道具 举报

1371

主题

1613

帖子

10

金钱

管理员

Rank: 9Rank: 9Rank: 9

积分
22905
 楼主| 发表于 2026-8-29 21:50:11 | 显示全部楼层
encoded_input = tokenizer(sentences, padding=True, truncation=True, return_tensors='pt')也可以写为:
encoded_input = tokenizer(sentences)

下载训练好的模型,直接config设置模型参数,
config = AutoConfig.from_pretrained(model_dir)
model = AutoModel.from_config(config)

模型输入等效:
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']) )


算法QQ  3283892722
群智能算法链接http://halcom.cn/forum.php?mod=forumdisplay&fid=73
回复 支持 反对

使用道具 举报

1371

主题

1613

帖子

10

金钱

管理员

Rank: 9Rank: 9Rank: 9

积分
22905
 楼主| 发表于 2026-9-1 19:35:55 | 显示全部楼层
模型转化,
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' )
算法QQ  3283892722
群智能算法链接http://halcom.cn/forum.php?mod=forumdisplay&fid=73
回复 支持 反对

使用道具 举报

1371

主题

1613

帖子

10

金钱

管理员

Rank: 9Rank: 9Rank: 9

积分
22905
 楼主| 发表于 2026-9-12 23:46:25 | 显示全部楼层
  1. # -*- coding: utf-8 -*-
  2. """
  3. Spyder Editor
  4. This is a temporary script file.
  5. """
  6. from transformers import AutoTokenizer, AutoModel, AutoConfig
  7. import torch
  8. # Sentences we want sentence embeddings for
  9. sentences = ["RAG模型已初始化"]

  10. model_dir = r'D:/2-LearningCode/913_LM\RAG_WITIAI/bge-small-zh-1.5'
  11. # Load model from HuggingFace Hub
  12. tokenizer = AutoTokenizer.from_pretrained(model_dir)
  13. # model = AutoModel.from_pretrained('BAAI/bge-large-zh-v1.5')
  14. config = AutoConfig.from_pretrained(model_dir)
  15. model = AutoModel.from_config(config)
  16. model.eval()

  17. # torch.save(model.state_dict(), 'rag_'+ str(512) + '.pt')
  18. # model.load_state_dict(torch.load('rag_'+ str(512) + '.pt', map_location=torch.device('cpu') ))
  19. # model.eval()

  20. example1 = torch.randint(low=0, high=1000, size=(1, 512), dtype=torch.long).type(torch.LongTensor)
  21. example2 = torch.ones(1, 512).type(torch.LongTensor)
  22. example3 = torch.zeros(1, 512).type(torch.LongTensor)

  23. pt_model = torch.jit.trace(model, (example1,example2,example3), strict=False )
  24. pt_model.save( 'ragX_'+ str(512) + '.pt' )

  25. # 第二步,直接load,C++中是这样加载
  26. # model = torch.jit.load('ragX_'+ str(512) + '.pt')
  27. # model.eval()

  28. # Tokenize sentences
  29. # encoded_input = tokenizer(sentences, padding=True, truncation=True, return_tensors='pt')
  30. # for s2p(short query to long passage) retrieval task, add an instruction to query (not add instruction for passages)
  31. # encoded_input = tokenizer([instruction + q for q in queries], padding=True, truncation=True, return_tensors='pt')
  32. encoded_input = tokenizer(sentences)

  33. # Compute token embeddings
  34. with torch.no_grad():
  35.     # model_output = model(**encoded_input)
  36.     model_output = model( input_ids=torch.tensor(encoded_input['input_ids']),
  37.                          attention_mask=torch.tensor(encoded_input['attention_mask']),
  38.                          token_type_ids=torch.tensor(encoded_input['token_type_ids']) )
  39.     # Perform pooling. In this case, cls pooling.
  40.     sentence_embeddings = model_output[0][:, 0]
  41. # normalize embeddings
  42. sentence_embeddings = torch.nn.functional.normalize(sentence_embeddings, p=2, dim=1)
  43. print("Sentence embeddings:", sentence_embeddings)


复制代码
算法QQ  3283892722
群智能算法链接http://halcom.cn/forum.php?mod=forumdisplay&fid=73
回复 支持 反对

使用道具 举报

1371

主题

1613

帖子

10

金钱

管理员

Rank: 9Rank: 9Rank: 9

积分
22905
 楼主| 发表于 2026-9-12 23:46:56 | 显示全部楼层
python中测试,可用:
  1. from transformers import AutoTokenizer, AutoModel, AutoConfig
  2. import torch

  3. sentences = ["RAG模型已初始化"]

  4. model_dir = r'D:/2-LearningCode/913_LM\RAG_WITIAI/bge-small-zh-1.5'
  5. tokenizer = AutoTokenizer.from_pretrained(model_dir)
  6. config = AutoConfig.from_pretrained(model_dir)
  7. model = AutoModel.from_config(config)

  8. model.load_state_dict(torch.load('rag_'+ str(512) + '.pt', map_location=torch.device('cpu') ))
  9. model.eval()

  10. encoded_input = tokenizer(sentences)

  11. # Compute token embeddings
  12. with torch.no_grad():
  13.     # model_output = model(**encoded_input)
  14.     model_output = model( input_ids=torch.tensor(encoded_input['input_ids']),
  15.                          attention_mask=torch.tensor(encoded_input['attention_mask']),
  16.                          token_type_ids=torch.tensor(encoded_input['token_type_ids']) )
  17.     # Perform pooling. In this case, cls pooling.
  18.     sentence_embeddings = model_output[0][:, 0]
  19. # normalize embeddings
  20. sentence_embeddings = torch.nn.functional.normalize(sentence_embeddings, p=2, dim=1)
  21. print("Sentence embeddings:", sentence_embeddings)
复制代码
算法QQ  3283892722
群智能算法链接http://halcom.cn/forum.php?mod=forumdisplay&fid=73
回复 支持 反对

使用道具 举报

Python|Opencv|MATLAB|Halcom.cn ( 蜀ICP备16027072号 )

GMT+8, 2026-11-2 10:55 , Processed in 0.193675 second(s), 21 queries .

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

快速回复 返回顶部 返回列表