国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

langchain-ChatGLM源碼閱讀:模型加載

這篇具有很好參考價(jià)值的文章主要介紹了langchain-ChatGLM源碼閱讀:模型加載。希望對(duì)大家有所幫助。如果存在錯(cuò)誤或未考慮完全的地方,請(qǐng)大家不吝賜教,您也可以點(diǎn)擊"舉報(bào)違法"按鈕提交疑問(wèn)。

使用命令行參數(shù)初始化加載器

loader.py

def __init__(self, params: dict = None):
        """
        模型初始化
        :param params:
        """
        self.model = None
        self.tokenizer = None
        self.params = params or {}
        self.model_name = params.get('model_name', False)
        self.model_path = params.get('model_path', None)
        self.no_remote_model = params.get('no_remote_model', False)
        self.lora = params.get('lora', '')
        self.use_ptuning_v2 = params.get('use_ptuning_v2', False)
        self.lora_dir = params.get('lora_dir', '')
        self.ptuning_dir = params.get('ptuning_dir', 'ptuning-v2')
        self.load_in_8bit = params.get('load_in_8bit', False)
        self.bf16 = params.get('bf16', False)

        self.is_chatgmlcpp = "chatglm2-cpp" == self.model_name

模型實(shí)例化

shared.py

def loaderLLM(llm_model: str = None, no_remote_model: bool = False, use_ptuning_v2: bool = False) -> Any:
    """
    init llm_model_ins LLM
    :param llm_model: model_name
    :param no_remote_model:  remote in the model on loader checkpoint, if your load local model to add the ` --no-remote-model
    :param use_ptuning_v2: Use p-tuning-v2 PrefixEncoder
    :return:
    """
    # 默認(rèn)為chatglm2-6b-32k
    pre_model_name = loaderCheckPoint.model_name
    # model_config中chatglm2-6b-32k對(duì)應(yīng)參數(shù)
    llm_model_info = llm_model_dict[pre_model_name]

    if no_remote_model:
        loaderCheckPoint.no_remote_model = no_remote_model
    if use_ptuning_v2:
        loaderCheckPoint.use_ptuning_v2 = use_ptuning_v2

    # 如果指定了參數(shù),則使用參數(shù)的配置,默認(rèn)為none
    if llm_model:
        llm_model_info = llm_model_dict[llm_model]

    loaderCheckPoint.model_name = llm_model_info['name']
    # 默認(rèn)為T(mén)HUDM/chatglm2-6b-32k
    loaderCheckPoint.pretrained_model_name = llm_model_info['pretrained_model_name']
    # 需手動(dòng)指定路徑
    loaderCheckPoint.model_path = llm_model_info["local_model_path"]
    # ChatGLMLLMChain
    if 'FastChatOpenAILLM' in llm_model_info["provides"]:
        loaderCheckPoint.unload_model()
    else:
        loaderCheckPoint.reload_model()
    # 根據(jù)名稱自動(dòng)加載類:<class 'models.chatglm_llm.ChatGLMLLMChain'>
    provides_class = getattr(sys.modules['models'], llm_model_info['provides'])
    # 將類實(shí)例化為模型對(duì)象
    modelInsLLM = provides_class(checkPoint=loaderCheckPoint)
    if 'FastChatOpenAILLM' in llm_model_info["provides"]:
        modelInsLLM.set_api_base_url(llm_model_info['api_base_url'])
        modelInsLLM.call_model_name(llm_model_info['name'])
        modelInsLLM.set_api_key(llm_model_info['api_key'])
    return modelInsLLM

loader.py

    def reload_model(self):
        self.unload_model()
        self.model_config = self._load_model_config()

        if self.use_ptuning_v2:
            try:
                prefix_encoder_file = open(Path(f'{os.path.abspath(self.ptuning_dir)}/config.json'), 'r')
                prefix_encoder_config = json.loads(prefix_encoder_file.read())
                prefix_encoder_file.close()
                self.model_config.pre_seq_len = prefix_encoder_config['pre_seq_len']
                self.model_config.prefix_projection = prefix_encoder_config['prefix_projection']
            except Exception as e:
                print(e)
                print("加載PrefixEncoder config.json失敗")

        self.model, self.tokenizer = self._load_model()

        if self.lora:
            self._add_lora_to_model([self.lora])

        if self.use_ptuning_v2:
            try:
                prefix_state_dict = torch.load(Path(f'{os.path.abspath(self.ptuning_dir)}/pytorch_model.bin'))
                new_prefix_state_dict = {}
                for k, v in prefix_state_dict.items():
                    if k.startswith("transformer.prefix_encoder."):
                        new_prefix_state_dict[k[len("transformer.prefix_encoder."):]] = v
                self.model.transformer.prefix_encoder.load_state_dict(new_prefix_state_dict)
                self.model.transformer.prefix_encoder.float()
                print("加載ptuning檢查點(diǎn)成功!")
            except Exception as e:
                print(e)
                print("加載PrefixEncoder模型參數(shù)失敗")
        # llama-cpp模型(至少vicuna-13b)的eval方法就是自身,其沒(méi)有eval方法
        if not self.is_llamacpp and not self.is_chatgmlcpp:
            self.model = self.model.eval()

清空顯存

在加載模型前先清空顯存
loader.py

    def unload_model(self):
        del self.model
        del self.tokenizer
        self.model = self.tokenizer = None
        self.clear_torch_cache()
        
    def clear_torch_cache(self):
        # 垃圾回收, 避免內(nèi)存泄漏和優(yōu)化內(nèi)存使用
        gc.collect()
        if self.llm_device.lower() != "cpu":
            # 檢測(cè)系統(tǒng)是否支持MPS,這是是Apple在Mac設(shè)備上用于GPU加速的框架
            if torch.has_mps:
                try:
                    from torch.mps import empty_cache
                    empty_cache()
                except Exception as e:
                    print(e)
                    print(
                        "如果您使用的是 macOS 建議將 pytorch 版本升級(jí)至 2.0.0 或更高版本,以支持及時(shí)清理 torch 產(chǎn)生的內(nèi)存占用。")
            elif torch.has_cuda:
                device_id = "0" if torch.cuda.is_available() and (":" not in self.llm_device) else None
                CUDA_DEVICE = f"{self.llm_device}:{device_id}" if device_id else self.llm_device
                with torch.cuda.device(CUDA_DEVICE):
                    # 釋放GPU顯存緩存中的任何未使用的內(nèi)存。
                    # PyTorch在GPU上申請(qǐng)和釋放內(nèi)存時(shí),部分內(nèi)存會(huì)保留在緩存中重復(fù)利用,
                    # empty_cache()可以釋放這些緩存memory。
                    torch.cuda.empty_cache()
                    # 用于CUDA IPC內(nèi)存共享的垃圾回收。
                    # 在多進(jìn)程GPU訓(xùn)練中,進(jìn)程間會(huì)共享部分內(nèi)存,
                    # ipc_collect()可以顯式收集共享內(nèi)存垃圾。
                    torch.cuda.ipc_collect()
            else:
                print("未檢測(cè)到 cuda 或 mps,暫不支持清理顯存")

加載模型調(diào)用鏈

loader.py_load_model方法
model = LoaderClass.from_pretrained(checkpoint,
                                                        config=self.model_config,
                                                        torch_dtype=torch.bfloat16 if self.bf16 else torch.float16,
                                                        trust_remote_code=True).half()
auto_factory.pyfrom_pretrained方法

包路徑:site-packages/transformers/models/auto/auto_factory.py
作用:將配置對(duì)象的類與模型類或?qū)ο蠼㈥P(guān)聯(lián),以便根據(jù)配置來(lái)獲取相應(yīng)的模型類或?qū)ο蟆_@通常用于管理不同配置下的模型選擇和實(shí)例化。例如,根據(jù)不同的配置選擇不同的模型架構(gòu)或模型參數(shù)。

cls.register(config.__class__, model_class, exist_ok=True)
modeling_utils.pyfrom_pretrained方法

包路徑:site-packages/transformers/modeling_utils.py
作用:因?yàn)闆](méi)有顯式指定模型路徑,所以只能通過(guò)緩存方式下載和加載。

                    resolved_archive_file = cached_file(pretrained_model_name_or_path, filename, **cached_file_kwargs)

                    # Since we set _raise_exceptions_for_missing_entries=False, we don't get an exception but a None
                    # result when internet is up, the repo and revision exist, but the file does not.
                    if resolved_archive_file is None and filename == _add_variant(SAFE_WEIGHTS_NAME, variant):
                        # Maybe the checkpoint is sharded, we try to grab the index name in this case.
                        resolved_archive_file = cached_file(
                            pretrained_model_name_or_path,
                            _add_variant(SAFE_WEIGHTS_INDEX_NAME, variant),
                            **cached_file_kwargs,
                        )
			
			...
			
        # We'll need to download and cache each checkpoint shard if the checkpoint is sharded.
        if is_sharded:
            # rsolved_archive_file becomes a list of files that point to the different checkpoint shards in this case.
            resolved_archive_file, sharded_metadata = get_checkpoint_shard_files(
                pretrained_model_name_or_path,
                resolved_archive_file,
                cache_dir=cache_dir,
                force_download=force_download,
                proxies=proxies,
                resume_download=resume_download,
                local_files_only=local_files_only,
                use_auth_token=token,
                user_agent=user_agent,
                revision=revision,
                subfolder=subfolder,
                _commit_hash=commit_hash,
            )
hub.pyget_checkpoint_shard_files方法

包路徑:site-packages/transformers/utils/hub.py
作用:第一次啟動(dòng)項(xiàng)目時(shí)下載模型到本地緩存。

    for shard_filename in tqdm(shard_filenames, desc="Downloading shards", disable=not show_progress_bar):
        try:
            # Load from URL
            cached_filename = cached_file(
                pretrained_model_name_or_path,
                shard_filename,
                cache_dir=cache_dir,
                force_download=force_download,
                proxies=proxies,
                resume_download=resume_download,
                local_files_only=local_files_only,
                use_auth_token=use_auth_token,
                user_agent=user_agent,
                revision=revision,
                subfolder=subfolder,
                _commit_hash=_commit_hash,
            )
modeling_utils.py_load_pretrained_mode方法

包路徑:site-packages/transformers/modeling_utils.py
作用:遍歷權(quán)重文件分片,逐一加載這些分片,但會(huì)跳過(guò)那些只包含磁盤(pán)上載權(quán)重的分片文件,顯示加載的進(jìn)度條,也就是下面這個(gè)東西,但此時(shí)模型權(quán)重還沒(méi)有加載到顯存中

langchain-ChatGLM源碼閱讀:模型加載,自然語(yǔ)言處理,神經(jīng)網(wǎng)絡(luò),langchain,python

            if len(resolved_archive_file) > 1:
                resolved_archive_file = logging.tqdm(resolved_archive_file, desc="Loading checkpoint shards")
            for shard_file in resolved_archive_file:
                # Skip the load for shards that only contain disk-offloaded weights when using safetensors for the offload.
                if shard_file in disk_only_shard_files:
                    continue
                state_dict = load_state_dict(shard_file)
回到loader.py_load_model方法

這里主要是為了把模型加載到顯存,可以使用多卡加載方式

                       else:
                            # 基于如下方式作為默認(rèn)的多卡加載方案針對(duì)新模型基本不會(huì)失敗
                            # 在chatglm2-6b,bloom-3b,blooz-7b1上進(jìn)行了測(cè)試,GPU負(fù)載也相對(duì)均衡
                            from accelerate.utils import get_balanced_memory
                            max_memory = get_balanced_memory(model,
                                                             dtype=torch.int8 if self.load_in_8bit else None,
                                                             low_zero=False,
                                                             no_split_module_classes=model._no_split_modules)
                            self.device_map = infer_auto_device_map(model,
                                                                    dtype=torch.float16 if not self.load_in_8bit else torch.int8,
                                                                    max_memory=max_memory,
                                                                    no_split_module_classes=model._no_split_modules)

                    model = dispatch_model(model, device_map=self.device_map)
  • 未執(zhí)行上述代碼之前,顯存占用為0
    langchain-ChatGLM源碼閱讀:模型加載,自然語(yǔ)言處理,神經(jīng)網(wǎng)絡(luò),langchain,python

  • 執(zhí)行max_memory = get_balanced_memory(…):在這一部分代碼中,通過(guò)調(diào)用 get_balanced_memory 函數(shù)來(lái)獲取一個(gè)適當(dāng)?shù)膬?nèi)存分配方案,執(zhí)行完后每個(gè)卡都會(huì)產(chǎn)生少量的顯存占用
    langchain-ChatGLM源碼閱讀:模型加載,自然語(yǔ)言處理,神經(jīng)網(wǎng)絡(luò),langchain,python

langchain-ChatGLM源碼閱讀:模型加載,自然語(yǔ)言處理,神經(jīng)網(wǎng)絡(luò),langchain,python

  • 執(zhí)行self.device_map = infer_auto_device_map(…):根據(jù)模型、數(shù)據(jù)類型、內(nèi)存分配等信息來(lái)推斷設(shè)備映射,將模型的不同部分分配到不同的設(shè)備上進(jìn)行計(jì)算。
    langchain-ChatGLM源碼閱讀:模型加載,自然語(yǔ)言處理,神經(jīng)網(wǎng)絡(luò),langchain,python
  • 執(zhí)行model = dispatch_model(model, device_map=self.device_map):根據(jù)生成的設(shè)備映射 將模型的不同部分分配到不同的設(shè)備上進(jìn)行計(jì)算。這樣,模型就可以利用多個(gè)GPU并行計(jì)算,以提高計(jì)算性能,模型權(quán)重被全部加載到顯存。

langchain-ChatGLM源碼閱讀:模型加載,自然語(yǔ)言處理,神經(jīng)網(wǎng)絡(luò),langchain,python

不過(guò)需要注意的一點(diǎn)是,目前這種多卡模型加載存在bug,一問(wèn)問(wèn)題就崩,建議指定單卡加載

langchain-ChatGLM源碼閱讀:模型加載,自然語(yǔ)言處理,神經(jīng)網(wǎng)絡(luò),langchain,python文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-658110.html

到了這里,關(guān)于langchain-ChatGLM源碼閱讀:模型加載的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來(lái)自互聯(lián)網(wǎng)用戶投稿,該文觀點(diǎn)僅代表作者本人,不代表本站立場(chǎng)。本站僅提供信息存儲(chǔ)空間服務(wù),不擁有所有權(quán),不承擔(dān)相關(guān)法律責(zé)任。如若轉(zhuǎn)載,請(qǐng)注明出處: 如若內(nèi)容造成侵權(quán)/違法違規(guī)/事實(shí)不符,請(qǐng)點(diǎn)擊違法舉報(bào)進(jìn)行投訴反饋,一經(jīng)查實(shí),立即刪除!

領(lǐng)支付寶紅包贊助服務(wù)器費(fèi)用

相關(guān)文章

  • Langchain-ChatGLM配置文件參數(shù)測(cè)試

    Langchain-ChatGLM配置文件參數(shù)測(cè)試

    1 已知可能影響對(duì)話效果的參數(shù)(位于configs/model_config.py文件): 其中可能對(duì)讀取知識(shí)庫(kù)影響較大的變量有CHUNK_SIZE(單段參考上下文的長(zhǎng)度),VECTOR_SEARCH_TOP_K(知識(shí)庫(kù)參考文段數(shù)量),和VECTOR_SEARCH_SCORE_THRESHOLD(知識(shí)庫(kù)匹配內(nèi)容需要達(dá)到的最小相關(guān)度)。本實(shí)驗(yàn)將通過(guò)向不同

    2024年02月16日
    瀏覽(21)
  • LangChain-ChatGLM在WIndows10下的部署

    LangChain-ChatGLM在WIndows10下的部署

    1、LangChain + ChatGLM2-6B 搭建個(gè)人專屬知識(shí)庫(kù)中的LangChain + ChatGLM2-6B 構(gòu)建知識(shí)庫(kù)這一節(jié):基本的邏輯和步驟是對(duì)的,但要根據(jù)Windows和現(xiàn)狀做很多調(diào)整。 2、沒(méi)有動(dòng)過(guò)model_config.py中的“LORA_MODEL_PATH_BAICHUAN”這一項(xiàng)內(nèi)容,卻報(bào)錯(cuò):對(duì)報(bào)錯(cuò)“LORA_MODEL_PATH_BAICHUAN”提供了重要解決思路,雖

    2024年02月13日
    瀏覽(21)
  • windows環(huán)境下的langchain-ChatGLM的本地部署

    windows環(huán)境下的langchain-ChatGLM的本地部署

    首先是項(xiàng)目開(kāi)源地址?https://github.com/imClumsyPanda/langchain-ChatGLM 下載這個(gè)項(xiàng)目的源碼非常簡(jiǎn)單,但運(yùn)行起來(lái)十分麻煩,各種環(huán)境的搭配簡(jiǎn)直是折磨人,尤其是電腦上缺少各種安裝環(huán)境的,我首先先列舉幾個(gè),例如conda安裝python的虛擬環(huán)境,用這個(gè)比較方便,還有Anoconda的安裝,

    2024年02月13日
    瀏覽(29)
  • 2M大小的PDF文檔上傳到LangChain-ChatGLM知識(shí)圖譜中,大致需要的時(shí)間

    對(duì)于將2M大小的PDF文檔上傳到LangChain-ChatGLM知識(shí)圖譜中,大致需要的時(shí)間如下: PDF到文本的提取轉(zhuǎn)換:若PDF內(nèi)容主要為文本,此步驟約需要1-2分鐘。 提取的文本經(jīng)過(guò)預(yù)處理與分析:此步驟需要對(duì)文本進(jìn)行分詞、命名實(shí)體識(shí)別等處理,約需要2-5分鐘。 抽取文本中的結(jié)構(gòu)化知識(shí)(實(shí)體、關(guān)

    2024年02月08日
    瀏覽(20)
  • CentOS7上部署langchain-chatglm或stable-diffusion可能遇到的Bug的解決方案

    CentOS7上部署langchain-chatglm或stable-diffusion可能遇到的Bug的解決方案

    進(jìn)入你的代碼目錄下 下載依賴 這里可能有的朋友會(huì)有問(wèn)題會(huì)出現(xiàn)某些包下載不了,這里建議直接使用阿里源即可,在確定你的cuda版本之后(使用nvidia-smi確定cuda版本) 命令行執(zhí)行 卸載掉剛才pip安裝的版本!!!!因?yàn)榇颂幇惭b的版本還缺少cuda的支持,確定卸載掉之后 執(zhí)行 此處X為

    2024年02月16日
    瀏覽(32)
  • LangChain:大型語(yǔ)言模型(LLMs)-- ChatGLM

    1. 介紹 LangChain 是一個(gè)領(lǐng)先的框架,用于構(gòu)建由大型語(yǔ)言模型(LLM)驅(qū)動(dòng)的應(yīng)用程序。在這個(gè)框架內(nèi),ChatGLM 作為一個(gè)重要的組件,為用戶提供了強(qiáng)大的雙語(yǔ)(中文-英文)對(duì)話功能。ChatGLM 基于通用的語(yǔ)言模型(GLM)框架,擁有數(shù)十億級(jí)別的參數(shù),確保了其對(duì)話的流暢性和準(zhǔn)確

    2024年04月09日
    瀏覽(36)
  • LangChain+ChatGLM整合LLaMa模型(二)

    LangChain+ChatGLM整合LLaMa模型(二)

    LangChain+ChatGLM大模型應(yīng)用落地實(shí)踐(一) LLaMa模型GitHub地址 添加LLaMa模型配置 在Langchain-ChatGLM/configs/model_config.py中l(wèi)lm_model_dict添加 啟用LLaMa模型 進(jìn)入Web UI選擇LLaMa模型 LLAMA-7B(中文提問(wèn)當(dāng)作翻譯回答了…看來(lái)訓(xùn)練的中文語(yǔ)料不太行,但是英文也算是答對(duì)了) 具體為什么LLaMa為什

    2024年02月14日
    瀏覽(18)
  • LangChain+ChatGLM大模型應(yīng)用落地實(shí)踐(一)

    LangChain+ChatGLM大模型應(yīng)用落地實(shí)踐(一)

    LangChain是一個(gè)近期非?;钴S的開(kāi)源代碼庫(kù),目前也還在快速發(fā)展中,旨在讓大家快速構(gòu)建自己的LLM對(duì)話產(chǎn)品。當(dāng)然,該框架也支持自定義接入其他機(jī)構(gòu)、企業(yè)開(kāi)源的LLMs的API和模型(比如:ChatGLM、文心一言等)。 屆時(shí),LangChain的版本已經(jīng)更新到0.0.123,目前保持著每天1發(fā)版的

    2024年02月14日
    瀏覽(34)
  • 【大語(yǔ)言模型】15分鐘快速掌握LangChain以及ChatGLM

    【大語(yǔ)言模型】15分鐘快速掌握LangChain以及ChatGLM

    LangChain 是一個(gè)強(qiáng)大的框架,可以簡(jiǎn)化構(gòu)建高級(jí)語(yǔ)言模型應(yīng)用程序的過(guò)程。 LangChain是一個(gè)強(qiáng)大的框架,旨在幫助開(kāi)發(fā)人員 使用語(yǔ)言模型構(gòu)建端到端的應(yīng)用程序 。 它提供了一套工具、組件和接口,可簡(jiǎn)化創(chuàng)建由大型語(yǔ)言模型 (LLM) 和聊天模型提供支持的應(yīng)用程序的過(guò)程 。LangC

    2024年02月12日
    瀏覽(35)
  • 【ChatGLM_02】LangChain知識(shí)庫(kù)+Lora微調(diào)chatglm2-6b模型+提示詞Prompt的使用原則

    【ChatGLM_02】LangChain知識(shí)庫(kù)+Lora微調(diào)chatglm2-6b模型+提示詞Prompt的使用原則

    運(yùn)行l(wèi)angchain-ChatGLM-master下面的webui.py文件 (1) 配置知識(shí)庫(kù) 新建知識(shí)庫(kù) 向知識(shí)庫(kù)當(dāng)中添加文件 支持上傳的數(shù)據(jù)格式:word、pdf、excel、csv、txt、文件夾等。但是此處我試了一下 (2) 文檔數(shù)據(jù)測(cè)試 word文檔測(cè)試: (3) 知識(shí)庫(kù)測(cè)試模式 知識(shí)庫(kù)測(cè)試只會(huì)返回輸入內(nèi)容在當(dāng)前知識(shí)庫(kù)當(dāng)中的

    2024年02月14日
    瀏覽(24)

覺(jué)得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請(qǐng)作者喝杯咖啡吧~博客贊助

支付寶掃一掃領(lǐng)取紅包,優(yōu)惠每天領(lǐng)

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包