[컴][머신러닝] E5-large-v2 로 블로그글에 대한 답변 얻기

E5-large-v2 로 블로그글에 대한 답변 얻기

Disclaimer

이글은 필자의 이해를 바탕으로 재작성했다. 틀린 부분이 있을 수 있다.

overview

보통 우리의 검색은 indexing 된 정보를 가져다 준다. 그래서 A라는 키워드를 넣으면, 그에 맞는 값들을 던져준다. 이것을 chatgpt 에게 대신할 수 있다. 다만 chatgpt 는 blog 의 모든 글을 읽고 그것을 재구성해서 우리에게 던져줄 수 있다.

이 e5-large-v2 모델은 질문을 던지면, 가지고 있는 답변 문장중에 가장 근접한 것을 던져준다.

Contrastive Learning

ML(machine learning)방법중 Contrastive Learning(대조적 학습)이 있다. self-supervised learning의 일종이다.

이 학습은 positive pair(양성쌍), negative pair(음성쌍)의 data 를 만들고, 이러한 쌍들을 이용해서 모델을 학습시키는 방법이다.

이 data pair 는 사람이 labeling 해서 줄 수도 있고, AI 가 특정 알고리즘을 이용해서 스스로 할 수 도 있다. 이렇게 얻어진 data 로 model 을 학습하게 되면, 이를 통해 이 model 은 데이터 간의 비슷한점(similarity)과 차이점(difference)을 이해하고 패턴을 학습하게 된다.

E5-large-v2 model

E5-large-v2 model 은 질문(query)과 그에 맞는 답변(passage)를 가지고 학습한 model이다.(query, passage 의 pair) 그래서 질문을 던지는 경우, 그 질문을 embdding 하고, 그 값을 현재 저장된 embedding 에서 similarity 가 높은 것들을 가져온다.

query 에 대한 embedding 을 뽑고, 이것을 저장된 embedding 인 blog-paragraphs 에서 찾아 본다. 그러면 유사한 query 를 찾아낼 수 있다. 그러면 그 query 에 딸려있는 passage 를 결과로 주면 된다.

llm similar blog-paragraphs -c 'query: what is LLM?'

HuggingFace Inference API

https://huggingface.co/intfloat/e5-large-v2 에서 ‘Inference API’ 로 테스트를 해보면 이 모델이 질문을 던질때 어떤 답변을 줄지 확인해 볼 수 있다.

  • Source Sentence 에는 내가 model 에 input 으로 넣고 싶은 값
  • Sentences to compare to 에는 input texts, 즉 내가 model 에게 줄 context

값을 넣으면 된다.

llm

pip install llm
llm install llm-sentence-transformers

자신이 쓰려는 model 을 local 에 설치한다.

llm sentence-transformers register intfloat/e5-large-v2 -a lv2

sentence transformer

embedding들을 위한 python framework 이다. 기술적인 문장(state-of-the-art sentence), 문서, 이미지에 대해 embedding 을 해준다. 원하는 model 을 선택하고, 그 model 을 기준으로 한 embedding 을 얻을 수 있다.

여기서 사용하는 pretrained model 은 HuggingFace 같은 곳에서 serve 하는 model들이다.

SentenceTransformer는 아래 예시를 보면 이해가 될 것이다.

#
# source from : [Usage](https://www.sbert.net/#usage)
#
from sentence_transformers import SentenceTransformer
model = SentenceTransformer('all-MiniLM-L6-v2')

#Our sentences we like to encode
sentences = ['This framework generates embeddings for each input sentence',
    'Sentences are passed as a list of string.',
    'The quick brown fox jumps over the lazy dog.']

#Sentences are encoded by calling model.encode()
embeddings = model.encode(sentences)

#Print the embeddings
for sentence, embedding in zip(sentences, embeddings):
    print("Sentence:", sentence)
    print("Embedding:", embedding)
    print("")

intfloat/e5-large-v2 · Hugging Face

from sentence_transformers import SentenceTransformer
model = SentenceTransformer('intfloat/e5-large-v2')
input_texts = [
    'query: how much protein should a female eat',
    'query: summit define',
    "passage: As a general guideline, the CDC's average requirement of protein for women ages 19 to 70 is 46 grams per day. But, as you can see from this chart, you'll need to increase that if you're expecting or training for a marathon. Check out the chart below to see how much protein you should be eating each day.",
    "passage: Definition of summit for English Language Learners. : 1  the highest point of a mountain : the top of a mountain. : 2  the highest level. : 3  a meeting or series of meetings between the leaders of two or more governments."
]
embeddings = model.encode(input_texts, normalize_embeddings=True)

local 의 model 사용

local 의 model 을 이용하려면 local 에 model 을 다운로드 하고, local path 를 적어주면 된다. (참고: How to load huggingface model/resource from local disk? - Stack Overflow)

huggingface 를 git clone 하면, model file들이 download 된다. 이것을 SentenceTransformer에서 사용하면 된다.

Reference

  1. Embedding paragraphs from my blog with E5-large-v2 | Simon Willison’s TILs

[컴] google SRE 팀이 20년간 사이트를 운영하면서 얻은 교훈

구글 / 레슨 / lesson /

google SRE 팀이 20년간 사이트를 운영하면서 얻은 교훈

20년전 구글:

  • 2개의 소규모 데이터 센터, 각각 수천개 서버를 보유
  • 서버끼리는 한쌍의 2.4G network link 로 ring 연결
  • private cloud 를 운영
  • Assigner, Autoreplacer, Babysitter 같은 python script 로 운영
  • 이 script 들은 각각의 서버이름들로 가득찬 config file들을 기반으로 동작했다.
  • 작은 DB 기기가 있었다. 이 DB는 개별서버에 대한 정보를 체계적이고, 안정적이게(durable) 유지하는데 도움을 줬다.
  • 다음 이유로 script들과 config 들을 사용했다.
    • 일반적인 문제들을 자동으로 해결하기위해
    • 작은 서버 무리를 관리하는데 필요한 수작업을 줄이기 위해

현재:

2016년 Youtube global outage 에서 얻은 교훈

YouTube’s distributed memory caching system 으로 글로벌한 중단(global outage)를 15분간 경험으로 얻은 3가지 교훈

  1. The riskiness of a mitigation should scale with the severity of the outage (장애 완화조치의 위험성은 장애(outage)의 심각성에 비례한다.)
    • SRE 팀은 장애를 해결하기위해 한 조치가, 장애 자체보다 더 큰 위험을 초래한 경험이 있다.
    • 유투브 팀이 장애완화로 load-shedding을 했는데(일부 서비스나 기능을 의도적으로 중단시키는 방법), 이것이 장애를 해결하진 못하고, 이로 인해 연쇄적인 문제가 터졌다.
    • 장애상황에서는 모니터링과 상황의 심각성을 평가해야만 하고, 그리고 나서 장애의 심각성과 비슷한 수준의 위험을 갖는 장애완화조치(mitigation path)를 선택해야만 한다.
  2. Recovery mechanisms should be fully tested before an emergency (복구 절차들은 긴급상황전에 완전히 테스트돼야만 한다.)
    • 복구절차에 대해서 다음사항에 대해 테스트해라. 이것이 이 행동이 수행될때 위험을 줄여줄 것이다.
      • 그것이 원하는대로 동작하는지
      • 당신이 그것을 어떻게 사용하는지 아는지
    • 이번 중단을 겪고, 복구과정 testing 에 2배의 시간을 할당함.
  3. Canary all changes (모든 변화들을 미리 점검해라)

Google calendar 이슈 에서 얻은 교훈

  1. Have a “Big Red Button” (큰 빨간 버튼을 가져라)
    • 잠재적으로 위험한 작업을 하기전에 어떤것이 빨간 버튼들이 될 지 파악하는것이 중요하다.
    • 예를 들어, 어떤 것을 작업했는데, 그것이 퍼지기전에 plug 를 뽑아서 막을 수 있다면 그것이 빨간버튼이 되는 것이다.
    • Generic mitigations – O’Reilly
  2. Unit tests alone are not enough - integration testing is also needed (유닛테스트들 만 하는 것은 충분치 않다. 통합테스트 또한 필요하다.)
    • 유닛테스트는 runtime 환경과, 모든 production 의 요구사항을 그대로 복제해서 하는 테스트가 아니다.
    • 우리는 통합테스트들을 cold start 를 수행할 수 있다는 것을 확인하는데 사용할 수 있다.
    • 우리가 원하는 대로 동작하는가?
    • 구성요소들(components)가 우리가 원하는대로 함께 동작하는가?
    • 이 component 들이 성공적으로 우리가 원하는 system을 만드는가?
    • 우리의 test들이 실제 사용방법을 따르지 않았다. 그결과로 많은 테스트들이 변경이 실제로 어떻게 수행될지 평가하는데 도움이 되지 않았다.

2017년 2월 사건의 교훈

OAuth token 이 사용불가 되자 많은 기기가 logout 하고, OnHub 및 google wifi 기기가 공장초기화를 수행했다. 수동 계정복구 요청이 10배 급증.

  1. COMMUNICATION CHANNELS! AND BACKUP CHANNELS!! AND BACKUPS FOR THOSE BACKUP CHANNELS!!!

    • Google Hangout과 , Google Meet 로 사건을 관리하려 했지만, 사람들이 log out 돼서 연락이 안됐다.
    • 테스트가 된 의존성없는 대체 소통 채널들을 가져야만 한다.
    • 이 사건은 graceful degradation | Google - Site Reliability Engineering 에 대한 더 나은 이해를 하게 해줬다.
  2. Intentionally degrade performance modes (의도적인 성능저하 모드)

    • 모든것이 작동하지 않더라도, 최소의 기능이 꾸준히 제공되도록 하는 것이 때로는 더 일관된 사용자경험을 제공할 수 있기도 한다.
    • 신중하고, 의도적인 저하된 성능모드를 구축했다. 성능저하도 gracefully 하게 이뤄져야 하고, 예외적인 상황에서도 동작해야 한다.

자연적인 재해, 또는 사이버 공격등을 막으려면:

  1. Test for Disaster resilience (재해 복원력 테스트)
    • Resiliance testing 은 오류, 대기시간 또는 중단이 발생해도 서비스나 시스템이 유지될 수 있는지 확인
    • recovery testing 은 완전한 shutdown 된 이후에 다시 homeostasis(항상성) 로 돌아갈 수 있는지를 확인
    • 둘 다 사업의 연속적인 전략에 중요한 부분이 돼야 한다.
    • 유용한 활동: 다같이 앉아서 만약의 사태가 일어났을때 시나리오를 살펴보는 것
  2. Automate your mitigations (재해복구 자동화)
    • 2023년 3월, 몇몇 데이터 센터에서 여러 네트워킹 장치에 거의 동시에 장애가 발생하여 광범위한 패킷 손실이 발생
    • 이런 경우 복구하는 동작을 자동화 해놓으면, MTTR(mean time to resolution, 해결평균시간)을 줄일 수 있다.
    • 만약 특정 사건이 일어날때 왜 그 복구방법을 자동으로 실행할 수 없나? 때론 복구를 먼저해서 사용자영향을 피하고, 주요원인을 저장하는 것이 낫기도 하다.
  3. Reduce the time between rollouts, to decrease the likelihood of the rollout going wrong (배포(rollout)들 간의 시간을 줄여서 배포(rollout)가 잘못될 가능성을 줄인다.)
    • 2022년 3월, 결제 시스템의 광범위한 중단
    • database field 한개를 지웠는데, 그것이 문제가 됨.
    • 그 field 를 사용하는 모든 code를 그전에 지웠기 때문에 문제는 없었다.
    • 시스템의 한부분의 rollout 이 느렸는데, 그로인해 그 filed 가 live system 에서 사용되게 되었다.
    • 여러 구성요소가 있는 복잡한 시스템에서 이런 배포사이에 긴 지연이 있으면, 변경사항에 대한 안정성을 추측하기가 어려워 진다.
    • 빈번한 rollout 이 이런 종류의 실패에 대한 갑작스러운 놀람을 줄여준다.
    • Use Four Keys metrics like change failure rate to measure your DevOps performance | Google Cloud Blog
  4. A single global hardware version is a single point of failure (하나의 글로벌 하드웨어 버전은 실패 지점이 된다.)
    • 중요한 기능을 하는 기기가 특정 모델을 사용하는 것이 좀 더 간단한 운영과 유지를 하게 해주긴 한다.
    • 그러나 그 모델이 문제가 있을 경우, 중요한 기능은 더이상 동작하지 않는다.
    • 2020년 3월, 네트워킹장비가 발견되지 않은 zero-day bug 가 있었는데, 트래픽패턴의 변화가 생겨서 그 버그가 터져나왔다.
    • 네트워크 모두에 같은 모델과 버전의 기기들이 사용중이었어서, 상당한 지역적 중단은 발생했다.
    • 높은 우선순위 트래픽을 잘 동작하는 다른 기기로 전달해주는 여러개의 network backbone 들이 존재해서 전채적인 중단을 막을 수 있었다.
    • diverse infrastructure 를 유지하는 것은 그 자체로 비용이 들지만, 이것이 완전한 서비스 장애를 벗어나게 해줄 수 있다.

See Also

  1. Lessons Learned from Twenty Years of Site Reliability Engineering | Hacker News : 다양한 경험과 관련된 이야기들
  2. Building Secure and Reliable Systems
  3. > Automate your mitigations Think long and hard about this one. Multiple times i… | Hacker News : 자동화된 복구처리가 가져다 주는 복잡성과의 균형을 잡아야 한다.

[컴] CloudWatchFullAccess 와 CloudWatchFullAccessV2 의 차이

diff / policy / CloudWatchFullAccess / CloudWatchFullAccessV2

CloudWatchFullAccess 와 CloudWatchFullAccessV2 의 차이

  • 좀 더 명시적이 됐다. 이전의 *(asterisk)로 표현했던 부분을 개별 객체로 바꿨다.
  • Sid 가 추가됨
json policy document 비교

Reference

  1. CloudWatchFullAccessV2 - AWS Managed Policy
  2. CloudWatchFullAccess - AWS Managed Policy

[컴] wsl2 에서 microk8s 사용

kubernetes dashboard 접근방법 / 사용법 / 쿠베 / 쿠버네티스

wsl2 에서 microk8s 사용

sudo apt update && sudo apt upgrade -y
sudo snap install microk8s --classic
sudo usermod -a -G microk8s ${USER}
microk8s.kubectl get node

kubernetes dashboard 사용

microk8s enable dns dashboard storage
microk8s.kubectl get all --all-namespaces

curl https://10.152.183.192 --insecure 로 접근하면 된다.

windows 에서 wsl2 의 kubernetes에 접근

windows 에서 wsl2 에 접근하려면 kubectl proxy 를 이용하면 된다.

# wsl2 에서 proxy 를 띄운다.
$ kubectl proxy

windows에서 다음 url 로 접근한다.

http://localhost:8001/api/v1/namespaces/kube-system/services/https:kubernetes-dashboard:/proxy/#/login

login

kubernetes dashboard의 login 에서 token 으로 login 하는 option 이 있다. 그것으로 login 하면 된다.

token 생성은 wsl2 에서 다음처럼 하면 된다.

token=$(microk8s.kubectl -n kube-system get secret | grep default-token | cut -d " " -f1) microk8s.kubectl -n kube-system describe secret $token

See Also

[컴] wsl2 에서 minikube 실행

kubernetes 실행/ 쿠베 / 쿠버네티스 실행 / dev local / k8s windows

wsl2 에서 minikube 실행

1. docker 설치

  1. 필요한 package설치

    sudo apt-get install -y \
        apt-transport-https \
        ca-certificates \
        curl \
        software-properties-common
  2. add official Docker PGP key

    curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -
  3. add repo

    • add repo:

      sudo add-apt-repository \
         "deb [arch=amd64] https://download.docker.com/linux/ubuntu \
         $(lsb_release -cs) \
         stable"
    • package update:

      sudo apt-get update -y
  4. install docker community edition :

    sudo apt-get install -y docker-ce
  5. docker group 에 추가

    sudo usermod -aG docker $USER && newgrp docker

systemctl 설치

git clone https://github.com/DamionGans/ubuntu-wsl2-systemd-script.git
cd ubuntu-wsl2-systemd-script/
bash ubuntu-wsl2-systemd-script.sh

sudo apt install -y conntrack

systemd 사용

2. minikube 설치

minikube 설치:

# Download the latest Minikube
curl -Lo minikube https://storage.googleapis.com/minikube/releases/latest/minikube-linux-amd64

# Make it executable
chmod +x ./minikube

# Move it to your user's executable PATH
sudo mv ./minikube /usr/local/bin/

#Set the driver version to Docker
minikube config set driver docker

kubectl 설치:

이것이 필요한지는 확인이 필요

curl -LO "https://dl.k8s.io/release/$(curl -L -s https://dl.k8s.io/release/stable.txt)/bin/linux/amd64/kubectl"

# Make it executable
chmod +x ./kubectl

# Move it to your user's executable PATH
sudo mv ./minikube /usr/local/bin/

3. minikube 실행

namh@DESKTOP-H:~$ minikube start
😄  minikube v1.31.2 on Ubuntu 20.04 (amd64)
✨  Using the docker driver based on user configuration
📌  Using Docker driver with root privileges
👍  Starting control plane node minikube in cluster minikube
🚜  Pulling base image ...
💾  Downloading Kubernetes v1.27.4 preload ...
    > preloaded-images-k8s-v18-v1...:  393.21 MiB / 393.21 MiB  100.00% 10.18 M
    > gcr.io/k8s-minikube/kicbase...:  447.62 MiB / 447.62 MiB  100.00% 10.86 M
🔥  Creating docker container (CPUs=2, Memory=3900MB) ...
❗  This container is having trouble accessing https://registry.k8s.io
💡  To pull new external images, you may need to configure a proxy: https://minikube.sigs.k8s.io/docs/reference/networking/proxy/
🐳  Preparing Kubernetes v1.27.4 on Docker 24.0.4 ...
    ▪ Generating certificates and keys ...
    ▪ Booting up control plane ...
    ▪ Configuring RBAC rules ...
🔗  Configuring bridge CNI (Container Networking Interface) ...
    ▪ Using image gcr.io/k8s-minikube/storage-provisioner:v5
🔎  Verifying Kubernetes components...
🌟  Enabled addons: storage-provisioner, default-storageclass
🏄  Done! kubectl is now configured to use "minikube" cluster and "default" namespace by default
$ kubectl get nodes -o wide
NAME       STATUS   ROLES           AGE     VERSION   INTERNAL-IP    EXTERNAL-IP   OS-IMAGE             KERNEL-VERSION                       CONTAINER-RUNTIME
minikube   Ready    control-plane   7m50s   v1.27.4   192.168.49.2   <none>        Ubuntu 22.04.2 LTS   5.15.133.1-microsoft-standard-WSL2   docker://24.0.4

stop | minikube


$ minikube stop

Reference

  1. Install Minikube in WSL 2 with Kubectl and Helm - Virtualization Howto

[컴] 차세대 기록 장치, 유리

 

https://m.clien.net/service/board/news/18370348?od=T31&po=1&category=0&groupCd= 유리 가 저장장치로 쓰인다.

disk / storage / 영구적인 저장소 / 디스크 / 스토리지 / ssd / cd / 테이프 / 데이터센터 저장

차세대 기록 장치, 유리

  • ultrafast femtosecond laser 사용
  • 현재 기술은 plate 하나에 TB 저장 가능
  • datacenter 에 쓰일 것이라고.[ref. 2]
  • 대략 1만년정도 보존 가능하다. (기존의 자기 저장소는 보존기간이 5년정도다.)

Reference

  1. Project Silica proof of concept stores Warner Bros. ‘Superman’ movie on quartz glass
  2. Sealed in glass – Microsoft Unlocked

[컴] gmail 첨부파일 한번에 다운로드 하는 법

gmail attachment download / 지메일 / at once /지메일 첨부파일 백업방법

gmail 첨부파일 한번에 다운로드 하는 법

gmail 의 메일중 첨부파일이 있는 것들이 있다. 이것들을 전부 한번에 다운로드 받는 툴이다.

절차:

  1. settings 에서 계정 설정을 한다.
  2. folder/files –> Selected Folders –> 이름에 들어갈 필드 정하기 –> 하단에서 원하는 folder 선택 –> download