python_code stringlengths 0 992k | repo_name stringlengths 8 46 | file_path stringlengths 5 162 |
|---|---|---|
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from typing import Callable, Optional
import torch
from torch import nn, Tensor
from torchmultimodal.modules.l... | EXA-1-master | exa/libraries/multimodal-main/torchmultimodal/modules/encoders/bert_text_encoder.py |
import os
import pandas as pd
from tqdm import tqdm
BASE_URL="https://archive.org/download/stackexchange/"
table = pd.read_html(BASE_URL)[0]
sources = [x.replace(" (View Contents)", "") for x in table['Name'].tolist()]
sources = [x for x in sources if x.endswith(".7z")]
for source in tqdm(sources):
# if ".meta." ... | EXA-1-master | exa/libraries/data_prep/RedPajama-Data/data_prep/stack_exchange/download.py |
EXA-1-master | exa/libraries/data_prep/RedPajama-Data/data_prep/stack_exchange/__init__.py | |
import os
import json
LEMMA_DATA_DIR_SE_OUT = os.environ.get("LEMMA_DATA_DIR_SE_OUT", "./data/")
if __name__ == "__main__":
with open(os.path.join(LEMMA_DATA_DIR_SE_OUT,"token_counts", "tokens.json"), "r") as f:
counts = json.load(f)
'''
print a table of the counts
'''
print("|Idx|Site|Tok... | EXA-1-master | exa/libraries/data_prep/RedPajama-Data/data_prep/stack_exchange/print_stats.py |
import os
import json
import tiktoken
from multiprocessing import Pool
from transformers import AutoTokenizer
# enc = tiktoken.get_encoding("r50k_base")
enc = AutoTokenizer.from_pretrained(
"EleutherAI/pythia-6.9b-deduped",
# "gpt2"
)
def get_token_count(qa_pair):
# return len(enc.encode(qa_pair['text']))
... | EXA-1-master | exa/libraries/data_prep/RedPajama-Data/data_prep/stack_exchange/token_count.py |
import os
import json
import sys
import xml.etree.ElementTree as ET
from tqdm import tqdm
sys.path.append("./")
from src.stack_exchange.count import get_sites_count
LEMMA_DATA_DIR_SE = os.environ.get("LEMMA_DATA_DIR_SE", "./data/")
if os.path.exists(os.path.join(LEMMA_DATA_DIR_SE, "counts.json")):
with open(os.pa... | EXA-1-master | exa/libraries/data_prep/RedPajama-Data/data_prep/stack_exchange/filter.py |
import re
import os
import sys
import json
import fasttext
from bs4 import BeautifulSoup
from multiprocessing import Pool
sys.path.append("./")
site_name = ""
CLEANR = re.compile('<.*?>|&([a-z0-9]+|#[0-9]{1,6}|#x[0-9a-f]{1,6});')
def cleanhtml(raw_html):
raw_html = raw_html.replace("<li>", "\n*")
raw_html = ... | EXA-1-master | exa/libraries/data_prep/RedPajama-Data/data_prep/stack_exchange/post_processing.py |
import os
import json
from tqdm import tqdm
import xml.etree.ElementTree as ET
LEMMA_DATA_DIR_SE = os.environ.get("LEMMA_DATA_DIR_SE", "./data/stack_exchange/")
def get_sites_count(path=LEMMA_DATA_DIR_SE):
sites = os.listdir(path)
sites = [x for x in sites if x.endswith(".xml")]
counts = {}
for site i... | EXA-1-master | exa/libraries/data_prep/RedPajama-Data/data_prep/stack_exchange/count.py |
import argparse
from datasets import load_dataset
import pathlib
parser = argparse.ArgumentParser()
parser.add_argument("--data_dir", type=str, default=None,
help="Path to the wikipedia data directory.")
args = parser.parse_args()
LANGUAGES = [
"bg", "ca", "cs", "da", "de", "en", "es", "fr", "... | EXA-1-master | exa/libraries/data_prep/RedPajama-Data/data_prep/wiki/download.py |
EXA-1-master | exa/libraries/data_prep/RedPajama-Data/data_prep/wiki/__init__.py | |
import os
import json
from multiprocessing import Pool
from transformers import AutoTokenizer
print("start loading!")
enc = AutoTokenizer.from_pretrained(
"EleutherAI/pythia-6.9b-deduped",
)
print("end loading!")
def get_token_count(qa_pair):
return len(enc.tokenize(qa_pair['text']))
LEMMA_DATA_DIR_SE_OUT = ".... | EXA-1-master | exa/libraries/data_prep/RedPajama-Data/data_prep/wiki/token_count.py |
import os
import json
LEMMA_DATA_DIR_SE_OUT = "./data/wikipedia/"
LEMMA_DATA_SAVE_DIR = "./data/wikipedia/wiki-full.jsonl"
files = [x for x in os.listdir(os.path.join(LEMMA_DATA_DIR_SE_OUT)) if os.path.isfile(os.path.join(LEMMA_DATA_DIR_SE_OUT, x))]
files.sort()
with open(LEMMA_DATA_SAVE_DIR, "w") as fw:
for fil... | EXA-1-master | exa/libraries/data_prep/RedPajama-Data/data_prep/wiki/convert_format.py |
import argparse
import hashlib
import gzip
import json
import re
import uuid
from datetime import datetime
from typing import Dict, Union
import pathlib
parser = argparse.ArgumentParser()
parser.add_argument('--input', type=str, default=None)
parser.add_argument('--target_dir', type=str,
default="... | EXA-1-master | exa/libraries/data_prep/RedPajama-Data/data_prep/github/github_clean_dedup_local.py |
EXA-1-master | exa/libraries/data_prep/RedPajama-Data/data_prep/github/__init__.py | |
import argparse
from datetime import datetime
import json
import multiprocessing as mp
import os
import gzip
from transformers import AutoTokenizer
import pathlib
parser = argparse.ArgumentParser()
parser.add_argument('--data_file', type=str, default=None)
parser.add_argument('--target_dir', type=str, default=None)
a... | EXA-1-master | exa/libraries/data_prep/RedPajama-Data/data_prep/github/github_run_filter.py |
import argparse
import os
from transformers import AutoTokenizer
import json
import multiprocessing as mp
import pathlib
from datetime import datetime
parser = argparse.ArgumentParser()
parser.add_argument('--data_file', type=str, default=None)
args = parser.parse_args()
tokenizer = AutoTokenizer.from_pretrained("Ele... | EXA-1-master | exa/libraries/data_prep/RedPajama-Data/data_prep/github/github_token_count.py |
import argparse
import json
from datetime import datetime
from typing import Dict
import pathlib
parser = argparse.ArgumentParser()
parser.add_argument('--first_step_dir', type=str, default=None)
parser.add_argument('--target_dir', type=str, default=None)
args = parser.parse_args()
def get_timestamp() -> str:
r... | EXA-1-master | exa/libraries/data_prep/RedPajama-Data/data_prep/github/github_global_dedup.py |
import argparse
import json
from datetime import datetime
import pathlib
parser = argparse.ArgumentParser()
parser.add_argument(
'--first_step_dir', type=str,
default="./data/github/processed_v3"
)
parser.add_argument(
'--input', type=str,
default="data/github/processed_v3/run_ce60fbbc14684ed8b6590548... | EXA-1-master | exa/libraries/data_prep/RedPajama-Data/data_prep/github/github_merge_dedup.py |
from datasets import load_dataset
book_dataset = load_dataset("the_pile_books3")
for split, dataset in book_dataset.items():
dataset.to_json(f"./data/book/books3-{split}.jsonl")
pg19_dataset = load_dataset("pg19")
for split, dataset in pg19_dataset.items():
dataset.to_json(f"./data/book/pg19-{split}.jsonl") | EXA-1-master | exa/libraries/data_prep/RedPajama-Data/data_prep/book/download.py |
EXA-1-master | exa/libraries/data_prep/RedPajama-Data/data_prep/book/__init__.py | |
# Copyright 2023 Ontocord.ai, Together Computer, ETH Zürich, Stanford University
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unles... | EXA-1-master | exa/libraries/data_prep/RedPajama-Data/data_prep/book/dedup.py |
import os
import json
from multiprocessing import Pool
from transformers import AutoTokenizer
enc = AutoTokenizer.from_pretrained(
"EleutherAI/pythia-6.9b-deduped",
)
def get_token_count(qa_pair):
return len(enc.tokenize(qa_pair['text']))
LEMMA_DATA_DIR_SE_OUT = "./data/book/"
sites = [x for x in os.listdir(o... | EXA-1-master | exa/libraries/data_prep/RedPajama-Data/data_prep/book/token_count.py |
import argparse
from datetime import datetime
import json
import gzip
import os
import pathlib
import joblib
from joblib import Parallel, delayed
parser = argparse.ArgumentParser()
parser.add_argument('--data_dir', type=str, default="./data/c4/en")
parser.add_argument('--output_dir', type=str, default="./data/c4/proce... | EXA-1-master | exa/libraries/data_prep/RedPajama-Data/data_prep/c4/c4_reformat.py |
EXA-1-master | exa/libraries/data_prep/RedPajama-Data/data_prep/c4/__init__.py | |
import argparse
import boto3
from botocore.exceptions import ClientError
import configparser
import itertools
import numpy as np
import pathlib
parser = argparse.ArgumentParser()
parser.add_argument('--aws_config', type=str, help='aws config file')
parser.add_argument('--target_dir', type=str, default="./data/arxiv")
... | EXA-1-master | exa/libraries/data_prep/RedPajama-Data/data_prep/arxiv/run_download.py |
import concurrent.futures
from datetime import datetime
import fasttext
import json
import pathlib
import tarfile
from typing import List, Tuple, Dict, Union
import gzip
import tempfile
import uuid
import re
from utils import predict_lang, get_timestamp, format_arxiv_id
# suppress fasttext warning
fasttext.FastText.e... | EXA-1-master | exa/libraries/data_prep/RedPajama-Data/data_prep/arxiv/arxiv_cleaner.py |
from datetime import datetime
import fasttext
import re
from typing import List, Tuple
def get_timestamp() -> str:
return datetime.now().isoformat()
def predict_lang(
text: str, lang_model: fasttext.FastText._FastText, k=5
) -> Tuple[List[str], List[float]]:
r""" Predict top-k languages of text.
... | EXA-1-master | exa/libraries/data_prep/RedPajama-Data/data_prep/arxiv/utils.py |
import argparse
import os
from collections import defaultdict
from datetime import datetime
from transformers import AutoTokenizer
import json
import multiprocessing as mp
import pathlib
import pandas as pd
from tabulate import tabulate
parser = argparse.ArgumentParser()
parser.add_argument('--data_dir', type=str, def... | EXA-1-master | exa/libraries/data_prep/RedPajama-Data/data_prep/arxiv/token_count.py |
import argparse
import os
import uuid
import numpy as np
import pathlib
import tempfile
from typing import List
import joblib
from arxiv_cleaner import ArxivCleaner
parser = argparse.ArgumentParser()
parser.add_argument('--data_dir', type=str, default="./data/arxiv/src")
parser.add_argument('--target_dir', type=str,... | EXA-1-master | exa/libraries/data_prep/RedPajama-Data/data_prep/arxiv/run_clean.py |
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
from pathlib import Path
from setuptools import setup # type: ignore
setup(
name="cc_net",
version="1.0.0",
pa... | EXA-1-master | exa/libraries/data_prep/RedPajama-Data/data_prep/cc/cc_net/setup.py |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
#
"""
Main script to download a CC dump, remove duplicates, split by language and
filter the documents.
The pipeline parameters are described... | EXA-1-master | exa/libraries/data_prep/RedPajama-Data/data_prep/cc/cc_net/cc_net/mine.py |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
#
"""
Creates mono-lingual corpus from Wikipedia.
"""
import functools
import re
import subprocess
import urllib.request
from pathlib import ... | EXA-1-master | exa/libraries/data_prep/RedPajama-Data/data_prep/cc/cc_net/cc_net/get_wiki_cirrus.py |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
#
"""
Manipulate files containing one json per line.
"""
import argparse
import collections
import contextlib
import functools
import glob
imp... | EXA-1-master | exa/libraries/data_prep/RedPajama-Data/data_prep/cc/cc_net/cc_net/jsonql.py |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
#
import functools
import itertools
import logging
import os
import sys
import time
import warnings
from pathlib import Path
from typing impor... | EXA-1-master | exa/libraries/data_prep/RedPajama-Data/data_prep/cc/cc_net/cc_net/execution.py |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
#
import sys
import time
import warnings
from typing import Iterable, Iterator, Sequence, Sized, Tuple, Type
import numpy as np
HASH_TYPE: T... | EXA-1-master | exa/libraries/data_prep/RedPajama-Data/data_prep/cc/cc_net/cc_net/flat_hash_set.py |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
#
import base64
import hashlib
import itertools
import urllib.parse
from pathlib import Path
from typing import Dict, Iterable, List, Optional... | EXA-1-master | exa/libraries/data_prep/RedPajama-Data/data_prep/cc/cc_net/cc_net/minify.py |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
#
import re
import unicodedata
UNICODE_PUNCT = {
",": ",",
"。": ".",
"、": ",",
"„": '"',
"”": '"',
"“": '"',
"«":... | EXA-1-master | exa/libraries/data_prep/RedPajama-Data/data_prep/cc/cc_net/cc_net/text_normalizer.py |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
#
import logging
import subprocess
from pathlib import Path
from typing import List
import func_argparse
import numpy as np
from cc_net impo... | EXA-1-master | exa/libraries/data_prep/RedPajama-Data/data_prep/cc/cc_net/cc_net/regroup.py |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
#
import argparse
import time
from pathlib import Path
from typing import Dict, List, Optional, Sequence, Tuple, Union
import kenlm # type: ... | EXA-1-master | exa/libraries/data_prep/RedPajama-Data/data_prep/cc/cc_net/cc_net/perplexity.py |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
#
| EXA-1-master | exa/libraries/data_prep/RedPajama-Data/data_prep/cc/cc_net/cc_net/__init__.py |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
#
import time
from typing import Dict, Optional
import sacremoses # type: ignore
from cc_net import jsonql, text_normalizer
class RobustT... | EXA-1-master | exa/libraries/data_prep/RedPajama-Data/data_prep/cc/cc_net/cc_net/tokenizer.py |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
#
"""
Tools to remove duplicate paragraphs across one or several shards.
"""
import argparse
import gc
import hashlib
import logging
import m... | EXA-1-master | exa/libraries/data_prep/RedPajama-Data/data_prep/cc/cc_net/cc_net/dedup.py |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
#
import contextlib
import functools
import logging
import re
import tempfile
import time
import urllib.request
from pathlib import Path
from ... | EXA-1-master | exa/libraries/data_prep/RedPajama-Data/data_prep/cc/cc_net/cc_net/process_wet_file.py |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
#
import func_argparse
import cc_net.mine
def main():
func_argparse.parse_and_call(cc_net.mine.get_main_parser())
if __name__ == "__... | EXA-1-master | exa/libraries/data_prep/RedPajama-Data/data_prep/cc/cc_net/cc_net/__main__.py |
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import argparse
import collections
from pathlib import Path
from typing import Dict, Optional
import fasttext # type: igno... | EXA-1-master | exa/libraries/data_prep/RedPajama-Data/data_prep/cc/cc_net/cc_net/split_by_lang.py |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
#
import contextlib
import functools
import gzip
import logging
import multiprocessing
from collections import defaultdict
from pathlib import... | EXA-1-master | exa/libraries/data_prep/RedPajama-Data/data_prep/cc/cc_net/cc_net/tools/dl_cc_100.py |
EXA-1-master | exa/libraries/data_prep/RedPajama-Data/data_prep/cc/cc_net/cc_net/tools/__init__.py | |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
#
"""
This code is used to train a fastText classifier to label document with DMOZ categories.
The data, distributed under the cc-by 3.0 lice... | EXA-1-master | exa/libraries/data_prep/RedPajama-Data/data_prep/cc/cc_net/cc_net/tools/make_dmoz_corpus.py |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
#
"""
Tools to search sentences in CC similar to sentences in another corpus.
"""
import functools
import logging
import math
import subproce... | EXA-1-master | exa/libraries/data_prep/RedPajama-Data/data_prep/cc/cc_net/cc_net/tools/expand_corpus.py |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
#
import json
from pathlib import Path
from typing import Iterable, Sequence
from cc_net import dedup, jsonql
from cc_net.dedup import str_ha... | EXA-1-master | exa/libraries/data_prep/RedPajama-Data/data_prep/cc/cc_net/tests/test_dedup.py |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
#
import cc_net.text_normalizer as txt
def test_unicode_punct():
weird = ",。、„”“«»1」「《》´∶:?!();–—.~’…━〈〉【】%"
replaced = ',.,""""""""... | EXA-1-master | exa/libraries/data_prep/RedPajama-Data/data_prep/cc/cc_net/tests/test_normalizer.py |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
#
from pathlib import Path
from cc_net import process_wet_file
def test_parsing():
sample = Path(__file__).parent / "data" / "sample.wa... | EXA-1-master | exa/libraries/data_prep/RedPajama-Data/data_prep/cc/cc_net/tests/test_parse_wet_file.py |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
#
import numpy as np
import pytest
from cc_net.flat_hash_set import HASH_TYPE, FlatHashSet, NaiveHashSet
def as_dict(flat_hash_set) -> dict... | EXA-1-master | exa/libraries/data_prep/RedPajama-Data/data_prep/cc/cc_net/tests/test_flat_hash_set.py |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
#
import pytest
def _request_is_disabled(self, *args, **kwargs):
raise Exception(
f"Your code tried to call 'request' with: {arg... | EXA-1-master | exa/libraries/data_prep/RedPajama-Data/data_prep/cc/cc_net/tests/conftest.py |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
#
#
| EXA-1-master | exa/libraries/data_prep/RedPajama-Data/data_prep/cc/cc_net/tests/__init__.py |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
#
import time
from cc_net import jsonql, regroup
def check_regroup(tmp_path, regroup_fn, check_blocks_boundaries=False):
n_shards = 4
... | EXA-1-master | exa/libraries/data_prep/RedPajama-Data/data_prep/cc/cc_net/tests/test_regroup.py |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
#
import io
from pathlib import Path
from typing import Sequence
import numpy as np
import pytest
from cc_net import jsonql
def bar(small_... | EXA-1-master | exa/libraries/data_prep/RedPajama-Data/data_prep/cc/cc_net/tests/test_jsonql.py |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
#
import json
from pathlib import Path
import pytest
import cc_net
import cc_net.minify as minify
from cc_net import jsonql, process_wet_fil... | EXA-1-master | exa/libraries/data_prep/RedPajama-Data/data_prep/cc/cc_net/tests/test_minify.py |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
#
import inspect
import pickle
from pathlib import Path
import pytest
from cc_net import dedup, jsonql, perplexity, split_by_lang, tokenizer... | EXA-1-master | exa/libraries/data_prep/RedPajama-Data/data_prep/cc/cc_net/tests/test_transformer.py |
import glob, os
import json
import sys
import re
import hashlib
import gzip
import os
## Load data from the Wikipedia corpus
## And output them as label "__label__wiki"
#
files = ["cc_net/data/mined/wikipedia/en_head_0000.json.gz", "cc_net/data/mined/wikipedia/en_middle_0000.json.gz"]
unique = {}
i = 0
for f in files... | EXA-1-master | exa/libraries/data_prep/RedPajama-Data/data_prep/cc/classifier/create_corpus.py |
import glob, os
import json
import sys
import re
import hashlib
import gzip
import os
from multiprocessing import Pool
# Get all jobs.
# Each job corresponds to a file ends with .gz, with middle or head in it
#
jobs = []
os.chdir(sys.argv[1])
for file in glob.glob("*/*.gz"):
if ("middle" in file or "head" in file... | EXA-1-master | exa/libraries/data_prep/RedPajama-Data/data_prep/cc/classifier/classify.py |
import re
import argparse
parser = argparse.ArgumentParser()
parser.add_argument(
"--data",
"-d",
help="path to articles xml",
default="enwiki-20230401-pages-articles-multistream.xml",
)
parser.add_argument(
"--output",
"-o",
help="path to extracted urls file",
default="./extracted_url... | EXA-1-master | exa/libraries/data_prep/RedPajama-Data/data_prep/cc/classifier/extract_urls.py |
import glob, os
import json
import sys
import re
import hashlib
import gzip
import os
from multiprocessing import Pool
# Get all jobs.
# Each job corresponds to a file ends with .gz, with middle or head in it
#
jobs = []
os.chdir(sys.argv[1])
for file in glob.glob("*/*.gz"):
if ("middle" in file or "head" in file... | EXA-1-master | exa/libraries/data_prep/RedPajama-Data/data_prep/cc/dedup/dedup_phase1.py |
import glob, os
import json
import sys
import re
import hashlib
import gzip
import os
from multiprocessing import Pool, Value
import multiprocessing
import gc
# Get all jobs
#
jobs = []
os.chdir(sys.argv[1])
for file in glob.glob("*/*.gz"):
if ("middle" in file or "head" in file) and "dedup" not in file:
... | EXA-1-master | exa/libraries/data_prep/RedPajama-Data/data_prep/cc/dedup/dedup_phase2.py |
from megatron.data.indexed_dataset import MMapIndexedDataset
from transformers import AutoTokenizer
import argparse
# get the first argument as a file name, and an output file
parser = argparse.ArgumentParser()
parser.add_argument("file_name", help="the file name to read")
parser.add_argument("output_file", help="the... | EXA-1-master | exa/libraries/data_prep/RedPajama-Data/tokenization/count_tokens.py |
"""
Embed each row of a `.jsonl` file using a HuggingFace model and save the embeddings.
Authors: The Meerkat Team (Karan Goel, Sabri Eyuboglu, Arjun Desai)
License: Apache License 2.0
"""
import os
from argparse import ArgumentParser
import numpy as np
import pyarrow as pa
import pyarrow.compute as pc
import pyarrow... | EXA-1-master | exa/libraries/data_prep/RedPajama-Data/viz/embed_jsonl.py |
import os
from argparse import ArgumentParser
from glob import glob
import faiss
import numpy as np
from tqdm.auto import tqdm
def build_pca(
xb: np.ndarray,
d_in: int = 384,
d_out: int = 32,
):
pca = faiss.PCAMatrix(d_in, d_out)
pca.train(xb)
return pca
if __name__ == "__main__":
parse... | EXA-1-master | exa/libraries/data_prep/RedPajama-Data/viz/reduce_pca32.py |
import faiss
import numpy as np
import torch
import torch.nn.functional as F
from rich import print
from tqdm.auto import tqdm
from transformers import AutoModel, AutoTokenizer
def build_flat_index(
xb: np.ndarray,
d: int = 32,
):
index = faiss.IndexFlatL2(d)
index.add(xb)
return index
def load_... | EXA-1-master | exa/libraries/data_prep/RedPajama-Data/viz/utils.py |
import os
from argparse import ArgumentParser
import faiss
import numpy as np
def build_index(
xb: np.ndarray,
d: int = 32,
):
index = faiss.index_factory(d, "IVF100,PQ8")
# Sample 1_000_000 vectors to train the index.
xt = xb[np.random.choice(xb.shape[0], 1_000_000, replace=False)]
index.tra... | EXA-1-master | exa/libraries/data_prep/RedPajama-Data/viz/index_faiss.py |
"""
A Meerkat app for visualizing the Github subset of the RedPajama dataset.
Authors: The Meerkat Team (Karan Goel, Sabri Eyuboglu, Arjun Desai)
License: Apache License 2.0
"""
import numpy as np
import tempfile
from utils import extract_features_single, load_pca, create_model_and_tokenizer
import meerkat as mk
from... | EXA-1-master | exa/libraries/data_prep/RedPajama-Data/viz/main.py |
import os
import sys
import argparse
from os.path import join
from tools import *
import logging
from api import set_api_logger
from chat import ChatBot, Turn, set_chat_logger
import gradio as gr
args: argparse.Namespace = None
bot: ChatBot = None
def summarize_embed_one_turn(bot: ChatBot, dialogue_text, dialogue_te... | EXA-1-master | exa/libraries/SCM4LLMs/dialogue-ui-demo.py |
# coding=utf-8
import os
import sys
import time
import json
import pickle
import string
import tiktoken
from langdetect import detect_langs
LANG_EN = 'English'
LANG_ZH = 'Chinese'
LANG_UN = 'Unknown'
def detect_language(text):
# 获取主要语言列表
langs = detect_langs(text)
# 整理语言列表,将每个语言和其概率整理为一个字典
lang_dict =... | EXA-1-master | exa/libraries/SCM4LLMs/tools.py |
import os
import openai
import torch
import time
from tools import get_lines, time_cost, append_file
from transformers import AutoTokenizer, AutoModelForCausalLM
BLOOM_MODEL = None
BLOOM_TOKENIZER = None
LOCAL_API_LOGGER = None
def set_api_logger(one):
global LOCAL_API_LOGGER
LOCAL_API_LOGGER = one
class Key... | EXA-1-master | exa/libraries/SCM4LLMs/api.py |
import torch
import torch.nn.functional as F
import numpy as np
from api import *
import tiktoken
from tools import *
import json
from transformers import GPT2Tokenizer
from tools import load_jsonl_file, datetime2str, save_json_file, save_file
LOCAL_CHAT_LOGGER = None
def set_chat_logger(one):
global LOCAL_CHAT_LO... | EXA-1-master | exa/libraries/SCM4LLMs/summary.py |
import torch
import torch.nn.functional as F
import numpy as np
from api import *
import tiktoken
import json
from transformers import GPT2Tokenizer
from tools import load_jsonl_file, datetime2str, save_json_file, save_file
LOCAL_CHAT_LOGGER = None
def set_chat_logger(one):
global LOCAL_CHAT_LOGGER
LOCAL_CHAT_... | EXA-1-master | exa/libraries/SCM4LLMs/chat.py |
import os
import sys
import argparse
from os.path import join
from tools import *
import logging
from api import set_api_logger
from summary import SummaryBot, SummaryTurn, set_chat_logger
import gradio as gr
args: argparse.Namespace = None
bot: SummaryBot = None
# todo: 这部分长度可能会超长,需要动态设置一下。
def get_concat_input(use... | EXA-1-master | exa/libraries/SCM4LLMs/summary-ui-demo.py |
"""MosaicML LLM Foundry package setup."""
import os
import re
from setuptools import setup
_PACKAGE_NAME = 'llm-foundry'
_PACKAGE_DIR = 'llmfoundry'
_REPO_REAL_PATH = os.path.dirname(os.path.realpath(__file__))
_PACKAGE_REAL_PATH = os.path.join(_REPO_REAL_PATH, _PACKAGE_DIR)
# Read the repo version
# We can't use `... | EXA-1-master | exa/libraries/llm-foundry/setup.py |
# Copyright 2022 MosaicML LLM Foundry authors
# SPDX-License-Identifier: Apache-2.0
try:
import torch
from llmfoundry import optim, utils
from llmfoundry.data import (ConcatTokensDataset,
MixtureOfDenoisersCollator, NoConcatDataset,
Seq2Seq... | EXA-1-master | exa/libraries/llm-foundry/llmfoundry/__init__.py |
# Copyright 2022 MosaicML LLM Foundry authors
# SPDX-License-Identifier: Apache-2.0
from typing import List
from composer.core import Callback, State
from composer.loggers import Logger
__all__ = [
'GlobalLRScaling',
'LayerFreezing',
]
class GlobalLRScaling(Callback):
"""GlobalLRScaling.
This call... | EXA-1-master | exa/libraries/llm-foundry/llmfoundry/callbacks/resumption_callbacks.py |
# Copyright 2022 MosaicML LLM Foundry authors
# SPDX-License-Identifier: Apache-2.0
import contextlib
import os
import tempfile
from pathlib import Path
import torch
from composer.core import Callback, State
from composer.core.state import fsdp_state_dict_type_context
from composer.loggers import Logger
from composer... | EXA-1-master | exa/libraries/llm-foundry/llmfoundry/callbacks/monolithic_ckpt_callback.py |
# Copyright 2022 MosaicML LLM Foundry authors
# SPDX-License-Identifier: Apache-2.0
"""Periodically log generations to wandb from a set of prompts."""
from typing import List, Union, cast
import torch
import wandb
from composer.core import Callback, State
from composer.loggers import Logger, WandBLogger
from composer... | EXA-1-master | exa/libraries/llm-foundry/llmfoundry/callbacks/generate_callback.py |
# Copyright 2022 MosaicML LLM Foundry authors
# SPDX-License-Identifier: Apache-2.0
try:
from llmfoundry.callbacks.fdiff_callback import FDiffMetrics
from llmfoundry.callbacks.generate_callback import Generate
from llmfoundry.callbacks.monolithic_ckpt_callback import \
MonolithicCheckpointSaver
... | EXA-1-master | exa/libraries/llm-foundry/llmfoundry/callbacks/__init__.py |
# Copyright 2022 MosaicML LLM Foundry authors
# SPDX-License-Identifier: Apache-2.0
import gc
import torch
from composer.core import Callback, State
from composer.loggers import Logger
def gc_cuda():
"""Gargage collect Torch (CUDA) memory."""
gc.collect()
if torch.cuda.is_available():
torch.cuda... | EXA-1-master | exa/libraries/llm-foundry/llmfoundry/callbacks/scheduled_gc_callback.py |
# Copyright 2022 MosaicML LLM Foundry authors
# SPDX-License-Identifier: Apache-2.0
"""Monitor rate of change of loss."""
from __future__ import annotations
import torch
from composer.core import Callback, State
from composer.loggers import Logger
class FDiffMetrics(Callback):
"""Rate of chage of metrics.
... | EXA-1-master | exa/libraries/llm-foundry/llmfoundry/callbacks/fdiff_callback.py |
# Copyright 2022 MosaicML LLM Foundry authors
# SPDX-License-Identifier: Apache-2.0
import logging
import math
from typing import Callable, Optional, Tuple
import torch
from composer.utils import dist
from torch.optim.optimizer import Optimizer
log = logging.getLogger(__name__)
class DecoupledLionW(Optimizer):
... | EXA-1-master | exa/libraries/llm-foundry/llmfoundry/optim/lion.py |
# Copyright 2022 MosaicML LLM Foundry authors
# SPDX-License-Identifier: Apache-2.0
from llmfoundry.optim.adaptive_lion import DecoupledAdaLRLion, DecoupledClipLion
from llmfoundry.optim.lion import DecoupledLionW
__all__ = ['DecoupledLionW', 'DecoupledClipLion', 'DecoupledAdaLRLion']
| EXA-1-master | exa/libraries/llm-foundry/llmfoundry/optim/__init__.py |
# Copyright 2022 MosaicML LLM Foundry authors
# SPDX-License-Identifier: Apache-2.0
import collections
class OutlierDetector:
"""OutlierDetector.
This class implements an algorithm to detect outliers in sequential
numeric data (e.g. for gradient/moment norms in optimizers). It relies on a
delayed mo... | EXA-1-master | exa/libraries/llm-foundry/llmfoundry/optim/outlier_detection.py |
# Copyright 2022 MosaicML LLM Foundry authors
# SPDX-License-Identifier: Apache-2.0
import logging
import math
from typing import Callable, Optional, Tuple
import torch
from composer.utils import dist
from torch.optim.optimizer import Optimizer
from llmfoundry.optim.outlier_detection import OutlierDetector
log = lo... | EXA-1-master | exa/libraries/llm-foundry/llmfoundry/optim/adaptive_lion.py |
# Copyright 2022 MosaicML LLM Foundry authors
# SPDX-License-Identifier: Apache-2.0
import os
from typing import Union
from composer import algorithms
from composer.callbacks import (HealthChecker, LRMonitor, MemoryMonitor,
OptimizerMonitor, RuntimeEstimator,
... | EXA-1-master | exa/libraries/llm-foundry/llmfoundry/utils/builders.py |
# Copyright 2022 MosaicML LLM Foundry authors
# SPDX-License-Identifier: Apache-2.0
try:
from llmfoundry.utils.builders import (build_algorithm, build_callback,
build_icl_evaluators, build_logger,
build_optimizer, build_scheduler... | EXA-1-master | exa/libraries/llm-foundry/llmfoundry/utils/__init__.py |
# Copyright 2022 MosaicML LLM Foundry authors
# SPDX-License-Identifier: Apache-2.0
import math
from typing import Union
from composer.utils import dist
from omegaconf import DictConfig
from omegaconf import OmegaConf as om
def calculate_batch_size_info(global_batch_size: int,
device_m... | EXA-1-master | exa/libraries/llm-foundry/llmfoundry/utils/config_utils.py |
# Copyright 2022 MosaicML LLM Foundry authors
# SPDX-License-Identifier: Apache-2.0
from llmfoundry.models.hf import (ComposerHFCausalLM, ComposerHFPrefixLM,
ComposerHFT5)
from llmfoundry.models.mpt import (ComposerMPTCausalLM, MPTConfig,
MPTForCausa... | EXA-1-master | exa/libraries/llm-foundry/llmfoundry/models/__init__.py |
# Copyright 2022 MosaicML LLM Foundry authors
# SPDX-License-Identifier: Apache-2.0
from llmfoundry.models.hf import (ComposerHFCausalLM, ComposerHFPrefixLM,
ComposerHFT5)
from llmfoundry.models.mpt import ComposerMPTCausalLM
COMPOSER_MODEL_REGISTRY = {
'mpt_causal_lm': ComposerM... | EXA-1-master | exa/libraries/llm-foundry/llmfoundry/models/model_registry.py |
# Copyright 2022 MosaicML LLM Foundry authors
# SPDX-License-Identifier: Apache-2.0
"""Attention layers."""
import math
import warnings
from typing import Optional
import torch
import torch.nn as nn
from einops import rearrange
from torch import nn
from llmfoundry.models.layers.norm import LPLayerNorm
def _reset_... | EXA-1-master | exa/libraries/llm-foundry/llmfoundry/models/layers/attention.py |
# Copyright 2022 MosaicML LLM Foundry authors
# SPDX-License-Identifier: Apache-2.0
import torch
def _cast_if_autocast_enabled(tensor):
if torch.is_autocast_enabled():
if tensor.device.type == 'cuda':
dtype = torch.get_autocast_gpu_dtype()
elif tensor.device.type == 'cpu':
... | EXA-1-master | exa/libraries/llm-foundry/llmfoundry/models/layers/norm.py |
# Copyright 2022 MosaicML LLM Foundry authors
# SPDX-License-Identifier: Apache-2.0
from llmfoundry.models.layers.attention import (
ATTN_CLASS_REGISTRY, MultiheadAttention, MultiQueryAttention,
attn_bias_shape, build_alibi_bias, build_attn_bias, flash_attn_fn,
scaled_multihead_dot_product_attention, trito... | EXA-1-master | exa/libraries/llm-foundry/llmfoundry/models/layers/__init__.py |
# Copyright 2022 MosaicML LLM Foundry authors
# SPDX-License-Identifier: Apache-2.0
"""GPT Blocks used for the GPT Model."""
from typing import Dict, Optional, Tuple
import torch
import torch.nn as nn
from llmfoundry.models.layers.attention import ATTN_CLASS_REGISTRY
from llmfoundry.models.layers.norm import NORM_C... | EXA-1-master | exa/libraries/llm-foundry/llmfoundry/models/layers/blocks.py |
# Copyright 2022 MosaicML LLM Foundry authors
# SPDX-License-Identifier: Apache-2.0
from llmfoundry.models.mpt.configuration_mpt import MPTConfig
from llmfoundry.models.mpt.modeling_mpt import (ComposerMPTCausalLM,
MPTForCausalLM, MPTModel,
... | EXA-1-master | exa/libraries/llm-foundry/llmfoundry/models/mpt/__init__.py |
# Copyright 2022 MosaicML LLM Foundry authors
# SPDX-License-Identifier: Apache-2.0
"""A simple, flexible implementation of a GPT model.
Inspired by https://github.com/karpathy/minGPT/blob/master/mingpt/model.py
"""
import math
import warnings
from typing import List, Optional, Tuple, Union
import torch
import torc... | EXA-1-master | exa/libraries/llm-foundry/llmfoundry/models/mpt/modeling_mpt.py |
# Copyright 2022 MosaicML LLM Foundry authors
# SPDX-License-Identifier: Apache-2.0
"""A HuggingFace-style model configuration."""
from typing import Dict, Optional, Union
from transformers import PretrainedConfig
attn_config_defaults: Dict = {
'attn_type': 'multihead_attention',
'attn_pdrop': 0.0,
'att... | EXA-1-master | exa/libraries/llm-foundry/llmfoundry/models/mpt/configuration_mpt.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.