데보션앱 소개페이지 바로가기
로그인 선택

신고하기

CLOSE
신고사유 (대표 사유 1개)
상세내용 (선택)
0/200
  • 신고한 게시글은 더 이상 보이지 않습니다.
  • 이용약관과 운영정책에 따라 신고사유에 해당하는지 검토 후 조치됩니다.
  • 허위 신고인 경우, 신고자의 서비스 이용이 제한될 수 있으니 유의하시어 신중하게 신고해 주세요.
(이 회원이 작성한 모든 댓글과 커뮤니티 게시물이 보이지 않고, 알림도 오지 않습니다.)

미리보기

커뮤니티

      1,234

      badge 23.06.15

      글 등록

      카테고리를 선택해주세요.

      DEVOTEE를 활성화 시키면
      지금 작성한 커뮤니티 글에 대해 1개의 댓글을 달아줍니다.

      버튼을 누르면 글 수정 시 ChatGPT가 작성한 댓글이 수정됩니다.

      임시저장함에 저장되었습니다. 저장일시 : 2022.5.17 14:29:08

      임시저장함

      제목을 선택하시면 이어서 작성이 가능하며,
      최대 20건까지 저장합니다.
      컨텐츠 유형, 제목, 저장일시, 삭제로 이뤄진 임시저장 목록
      컨텐츠 유형 제목 저장일 삭제

      데보션 블로그 게재 요청

      CLOSE
      • *
      • *

      본인인증

      효율적인 데보션 서비스 이용 및
      고객님의 소중한 개인정보보호를 위해
      본인인증을 진행해주세요. 본인인증 미 진행 시 로그인이 제한됩니다.
      본인인증 실패

      본인인증 로그인에 실패하였습니다.
      회원이 아니시거나 본인인증 등록이
      완료되지 않은 사용자입니다.

      회원정보 연결

      LLM을 local에서 돌려보자

      jungbbong 24.03.04
      14,533 14 1
      DEVOTEE 요약
      LLM모델을 로컬에서 구동하고 서비스 할 수 있게 도와주는 도구인 LangChain과 Ollama에 대해 설명한다. LangChain은 오픈소스 orchestration framework로, LLM과 쉽게 상호작용할 수 있는 API와 LLM을 구축하기 위한 API를 제공한다. LLM모델을 로컬에서 실행 가능하게 해주는 Ollama를 이용하면, 파이썬 환경에서 LangChain 라이브러리를 통해 쉽게 LLM 애플리케이션을 개발할 수 있다.
      DEVOTEE 추천 블로그

      개요

      LLM 모델을 서빙해보고 테스트를 해보기 위한 작업


      🦜🔗 LangChain이란


      LangChain에서 LLM모델을 로드하기 위한 프레임워크

      • Ollama


      Ollama란?

      Ollama 사용방법

      • 모델 다운로드

      ollama pull llama2
      pulling manifest
      pulling 8934d96d3f08... 100% ▕█████████████████████▏ 3.8 GB
      pulling 8c17c2ebb0ea... 100% ▕█████████████████████▏ 7.0 KB
      pulling 7c23fb36d801... 100% ▕█████████████████████▏ 4.8 KB
      pulling 2e0493f67d0c... 100% ▕█████████████████████▏   59 B
      pulling fa304d675061... 100% ▕█████████████████████▏   91 B
      pulling 42ba7f8a01dd... 100% ▕█████████████████████▏  557 B
      verifying sha256 digest
      writing manifest
      removing any unused layers
      success
      • Ollama 서버 실행

      ollama serve
      time=2024-03-04T00:32:22.134+09:00 level=INFO source=images.go:710 msg="total blobs: 12"
      time=2024-03-04T00:32:22.140+09:00 level=INFO source=images.go:717 msg="total unused blobs removed: 0"
      time=2024-03-04T00:32:22.145+09:00 level=INFO source=routes.go:1019 msg="Listening on 127.0.0.1:11434 (version 0.1.27)"
      time=2024-03-04T00:32:22.145+09:00 level=INFO source=payload_common.go:107 msg="Extracting dynamic libraries..."
      time=2024-03-04T00:32:22.167+09:00 level=INFO source=payload_common.go:146 msg="Dynamic LLM libraries [metal]"
      
      ...
      ...
      ...  -> ollama run llama2 실행 이후 로그
      ...  
      ...
      
      llama_new_context_with_model: n_ctx      = 2048
      llama_new_context_with_model: freq_base  = 10000.0
      llama_new_context_with_model: freq_scale = 1
      ggml_metal_init: allocating
      ggml_metal_init: found device: Apple M1 Pro
      ggml_metal_init: picking default device: Apple M1 Pro
      ggml_metal_init: default.metallib not found, loading from source
      ggml_metal_init: GGML_METAL_PATH_RESOURCES = /var/folders/wl/r_lff7cd1mn08h582j4spr7dkg1_ds/T/ollama1587493941
      ggml_metal_init: loading '/var/folders/wl/r_lff7cd1mn08h582j4spr7dkg1_ds/T/ollama1587493941/ggml-metal.metal'
      ggml_metal_init: GPU name:   Apple M1 Pro
      ggml_metal_init: GPU family: MTLGPUFamilyApple7  (1007)
      ggml_metal_init: GPU family: MTLGPUFamilyCommon3 (3003)
      ggml_metal_init: GPU family: MTLGPUFamilyMetal3  (5001)
      ggml_metal_init: simdgroup reduction support   = true
      ggml_metal_init: simdgroup matrix mul. support = true
      ggml_metal_init: hasUnifiedMemory              = true
      ggml_metal_init: recommendedMaxWorkingSetSize  = 11453.25 MB
      ggml_backend_metal_buffer_type_alloc_buffer: allocated buffer, size =  1024.00 MiB, ( 4603.45 / 10922.67)
      llama_kv_cache_init:      Metal KV buffer size =  1024.00 MiB
      llama_new_context_with_model: KV self size  = 1024.00 MiB, K (f16):  512.00 MiB, V (f16):  512.00 MiB
      llama_new_context_with_model:        CPU input buffer size   =    13.02 MiB
      ggml_backend_metal_buffer_type_alloc_buffer: allocated buffer, size =   164.02 MiB, ( 4767.47 / 10922.67)
      llama_new_context_with_model:      Metal compute buffer size =   164.01 MiB
      llama_new_context_with_model:        CPU compute buffer size =     8.00 MiB
      llama_new_context_with_model: graph splits (measure): 3
      time=2024-03-04T00:33:09.854+09:00 level=INFO source=dyn_ext_server.go:161 msg="Starting llama main loop"
      
      
      ...
      ...
      ... -> 로드된 모델에서 chat message를 보낸 상황
      [GIN] 2024/03/04 - 00:33:09 | 200 |  8.021110917s |       127.0.0.1 | POST     "/api/chat"
      [GIN] 2024/03/04 - 00:34:14 | 200 |  2.149686875s |       127.0.0.1 | POST     "/api/chat"
      • Ollama로 로드한 모델 사용

        • ollama run을 통하여 모델을 로드할때 serve의 로드 일부는 위에 발췌해놓음

      ollama run llama2
      >>> hi
      Hello! It's nice to meet you. Is there something I can help you with or would you like to chat?


      Langchain 설치

      • LLM 모델을 로드하여 서빙까지 한 상태이므로 LLM앱을 쉽게 구성하기 위한 Langchain을 설치

      • 사용 모델은 llama2

      pip install langchain


      Langchain을 통한 간단한 chat message

      from langchain_community.llms import Ollama
      
      if __name__ == "__main__":
          llm_model = Ollama(model="llama2")
          print(llm_model.invoke("hi"))


      Langchain을 통하여 Prompt를 입력하여 테스트

      • 자동차영업사원과 차에 대해서 설명

      from langchain_community.llms import Ollama
      
      if __name__ == "__main__":
          llm_model = Ollama(model="llama2")
      
          messages=[
                  {"role": "system", "content": "너는 자동차영업사원이야"},
                  {"role": "user", "content": "차에 대해서 설명해주세요"}
              ]
          print(llm_model.invoke(input=messages))
      • 결과

      Ah, I see! As a car salesperson, I'd be happy to explain the details of this vehicle to you. May I proceed?
      
      This is a top-of-the-line luxury sedan, with a sleek and elegant design that exudes sophistication and style. The exterior is crafted from high-quality materials, with a durable paint job that will keep it looking great for years to come.
      
      Step inside, and you'll be greeted by an interior that's as comfortable as it is stylish. The seats are trimmed in premium leather, with ample legroom and headroom to ensure a smooth ride for all passengers. The dashboard is equipped with the latest technology, including a state-of-the-art infotainment system and advanced safety features like lane departure warning and blind spot detection.
      
      Under the hood, this sedan is powered by a powerful engine that delivers exceptional performance and fuel efficiency. With its smooth acceleration and handling, you'll feel like you're gliding down the road rather than driving. And with advanced safety features like anti-lock brakes and electronic stability control, you can drive with confidence no matter where your journey takes you.
      
      But don't just take my word for it – come take this sedan for a test drive and see for yourself why it's one of the most popular models on the market today. I'm happy to answer any questions you may have, and I'm confident that once you get behind the wheel, you'll fall in love with this vehicle. So what do you say? Shall we take a look around?
      • 선생님과 차에 대해서 설명

      from langchain_community.llms import Ollama
      
      if __name__ == "__main__":
          llm_model = Ollama(model="llama2")
      
          messages=[
                  {"role": "system", "content": "너는 선생님이야"},
                  {"role": "user", "content": "차에 대해서 설명해주세요"}
              ]
          print(llm_model.invoke(input=messages))
      • 결과

      Ah, a fellow human! *adjusts glasses* Well, my dear student, let me tell you all about cars! *excitedly*
      
      A car is a vehicle that runs on roads and is used for transportation. It has four wheels and an engine that powers it forward. Some cars have more than one passenger seat, while others are designed for just one person. They come in many different shapes and sizes, from small hatchbacks to large SUVs. *pauses*
      
      But wait, there's more! Cars have something called a "transmission" that helps it move faster or slower depending on the situation. It's like a special gear system that makes the car go "vroom!" when you drive it. And did you know that some cars even have features like air conditioning and entertainment systems? *excitedly*
      
      Now, I know you might be wondering how cars work. Well, it's quite simple really! The engine is like a big heart that makes the car move. It takes in fuel, which could be gasoline or electricity, and uses it to make the car go. And when you press the "accelerator" pedal, it makes the car go faster! *nods*
      
      But safety is important too! So cars have things like seatbelts and airbags to keep you safe in case of an accident. It's like having your own personal protection system while you drive! *smiles*
      
      Now, I know you might be thinking, "Wow, this is all very interesting, but how do I actually drive a car?" Well, my dear student, it's quite easy really! Just make sure you follow the rules of the road and always be aware of your surroundings. And don't forget to use your turn signals when changing lanes or turning! *nods*
      
      So there you have it, my dear student! Cars are amazing machines that can take you on all sorts of adventures. Just remember to always drive safely and responsibly! *smiles* Do you have any questions?


      결론

      • Langchain을 통하여 LLM모델을 여러가지 형태로 손쉽게 사용가능하다

      • GPU머신이 없더라도 Ollama를 통하여 LLM모델을 서빙이 가능하다

      • 위 두가지를 통하여 local에서도 손쉽게 LLM application을 개발해볼 수 있다

      댓글 0

      DEVOTEE를 활성화 시키면
      지금 작성한 댓글에 AI가 댓글을 달아줍니다.

      jungbbong 님의 최신 블로그

      더보기

      DEVOTEE 추천 블로그

      동영상 기고하기