-
Notifications
You must be signed in to change notification settings - Fork 4.6k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
support openai embedding for topic clustering #2729
Merged
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -16,6 +16,7 @@ | |
from sklearn.cluster import KMeans, AgglomerativeClustering | ||
import torch | ||
from tqdm import tqdm | ||
from openai import OpenAI | ||
|
||
from fastchat.utils import detect_language | ||
|
||
|
@@ -46,6 +47,8 @@ def read_texts(input_file, min_length, max_length, english_only): | |
line_texts = [ | ||
x["content"] for x in l["conversation"] if x["role"] == "user" | ||
] | ||
elif "turns" in l: | ||
line_texts = l["turns"] | ||
|
||
for text in line_texts: | ||
text = text.strip() | ||
|
@@ -77,14 +80,26 @@ def read_texts(input_file, min_length, max_length, english_only): | |
|
||
|
||
def get_embeddings(texts, model_name, batch_size): | ||
model = SentenceTransformer(model_name) | ||
embeddings = model.encode( | ||
texts, | ||
batch_size=batch_size, | ||
show_progress_bar=True, | ||
device="cuda", | ||
convert_to_tensor=True, | ||
) | ||
if model_name == "text-embedding-ada-002": | ||
client = OpenAI() | ||
texts = texts.tolist() | ||
|
||
embeddings = [] | ||
for i in tqdm(range(0, len(texts), batch_size)): | ||
text = texts[i : i + batch_size] | ||
responses = client.embeddings.create(input=text, model=model_name).data | ||
embeddings.extend([data.embedding for data in responses]) | ||
embeddings = torch.tensor(embeddings) | ||
else: | ||
model = SentenceTransformer(model_name) | ||
embeddings = model.encode( | ||
texts, | ||
batch_size=batch_size, | ||
show_progress_bar=True, | ||
device="cuda", | ||
convert_to_tensor=True, | ||
) | ||
|
||
embeddings = torch.nn.functional.normalize(embeddings, p=2, dim=1) | ||
return embeddings.cpu() | ||
|
||
|
@@ -218,6 +233,8 @@ def get_cluster_info(texts, labels, topk_indices): | |
) | ||
parser.add_argument("--show-top-k", type=int, default=200) | ||
parser.add_argument("--show-cut-off", type=int, default=512) | ||
parser.add_argument("--save-embeddings", action="store_true") | ||
parser.add_argument("--embeddings-file", type=str, default=None) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. this embedding cache is awesome! |
||
args = parser.parse_args() | ||
|
||
num_clusters = args.num_clusters | ||
|
@@ -229,7 +246,15 @@ def get_cluster_info(texts, labels, topk_indices): | |
) | ||
print(f"#text: {len(texts)}") | ||
|
||
embeddings = get_embeddings(texts, args.model, args.batch_size) | ||
if args.embeddings_file is None: | ||
embeddings = get_embeddings(texts, args.model, args.batch_size) | ||
if args.save_embeddings: | ||
# allow saving embedding to save time and money | ||
torch.save(embeddings, "embeddings.pt") | ||
else: | ||
embeddings = torch.load(args.embeddings_file) | ||
print(f"embeddings shape: {embeddings.shape}") | ||
|
||
if args.cluster_alg == "kmeans": | ||
centers, labels = run_k_means(embeddings, num_clusters) | ||
elif args.cluster_alg == "aggcls": | ||
|
@@ -249,7 +274,7 @@ def get_cluster_info(texts, labels, topk_indices): | |
with open(filename_prefix + "_topk.txt", "w") as fout: | ||
fout.write(topk_str) | ||
|
||
with open(filename_prefix + "_all.txt", "w") as fout: | ||
with open(filename_prefix + "_all.jsonl", "w") as fout: | ||
for i in range(len(centers)): | ||
tmp_indices = labels == i | ||
tmp_embeddings = embeddings[tmp_indices] | ||
|
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
sorry could you explain this a bit?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yes, input json file has different format. For examples, the 54K prompt json file you sent me uses "turns" to store the conversation prompts. I added support for json files that uses "turns".