text
stringlengths
1
93.6k
torch_dtype = torch.float32
elif self.dtype == 'bfloat16':
torch_dtype = torch.bfloat16
else:
raise ValueError(f"Unsupported dtype: {self.dtype}")
self.logger.info(f"Loading model from {self.pretrained_model_dir} with trust_remote_code={self.trust_remote_code} and dtype={torch_dtype}")
model = AutoGPTQForCausalLM.from_pretrained(self.pretrained_model_dir, quantize_config=quantize_config,
low_cpu_mem_usage=True, torch_dtype=torch_dtype, trust_remote_code=self.trust_remote_code)
self.logger.info(f"Starting quantization to {output_dir} with use_triton={self.use_triton}")
start_time = time.time()
model.quantize(traindataset, use_triton=self.use_triton, batch_size=self.batch_size, cache_examples_on_gpu=self.cache_examples)
self.logger.info(f"Time to quantize model at {output_dir} with use_triton={self.use_triton}: {time.time() - start_time:.2f}")
self.logger.info(f"Saving quantized model to {output_dir}")
model.save_quantized(output_dir, use_safetensors=True)
self.logger.info(f"Saving tokenizer to {output_dir}")
self.tokenizer.save_pretrained(output_dir)
self.logger.info("Done.")
def run_quantization(self):
#TODO: This is messy, should be dynamic
if self.dataset == 'wikitext':
traindataset = self.get_wikitext2()
elif self.dataset == 'code' or self.dataset == 'evol-instruct-code':
traindataset = self.get_code()
elif self.dataset == 'math' or self.dataset == 'maths' or self.dataset == 'camel-ai/math':
traindataset = self.get_math()
elif self.dataset == 'medical' or self.dataset == 'medical_meadow_wikidoc':
traindataset = self.get_medical()
elif self.dataset == 'spanish':
traindataset = self.get_spanish()
elif self.dataset == 'german' or self.dataset == 'germanquad':
traindataset = self.get_german()
elif self.dataset == 'french' or self.dataset == 'diverse_french_news':
traindataset = self.get_french()
elif self.dataset == 'c4':
traindataset = self.get_c4()
else:
self.logger.error(f"Unsupported dataset: {self.dataset}")
raise ValueError(f"Unsupported dataset: {self.dataset}")
abort = False
iterations=[]
for bits in self.bits:
for group_size in self.group_size:
for desc_act in self.desc_act:
for damp in self.damp:
desc_act = desc_act == 1 and True or False
iterations.append({"bits": bits, "group_size": group_size, "desc_act": desc_act, "damp": damp})
num_iters = len(iterations)
if num_iters > 1:
logger.info(f"Starting {num_iters} quantizations.")
count=1
for iteration in iterations:
if abort:
break
if self.stop_file is not None and os.path.exists(self.stop_file):
self.logger.info(f"Stopping as {self.stop_file} exists")
abort = True
break
bits = iteration['bits']
group_size = iteration['group_size']
desc_act = iteration['desc_act']
damp = iteration['damp']
try:
if self.make_folder:
output_dir = os.path.join(self.output_dir_base, f"{bits}bits-{group_size}g-desc_act_{desc_act}-damp_{damp}")
else:
output_dir = self.output_dir_base
os.makedirs(output_dir, exist_ok=True)
try:
if num_iters > 1:
self.logger.info(f"Starting quantization {count}/{num_iters}")
self.logger.info(f"Quantising with bits={bits} group_size={group_size} desc_act={desc_act} damp={damp} to {output_dir}")
self.quantize(output_dir, traindataset, bits, group_size, desc_act, damp)
except KeyboardInterrupt:
logger.error(f"Aborted. Will delete {output_dir}")
os.rmdir(output_dir)
abort = True
except:
raise
finally:
count += 1
if __name__ == "__main__":
import argparse
logger = logging.getLogger()
logging.basicConfig(format="%(asctime)s %(levelname)s [%(name)s] %(message)s",
level=logging.INFO, datefmt="%Y-%m-%d %H:%M:%S")
parser = argparse.ArgumentParser(description='AutoGPTQ quantize')
parser.add_argument('pretrained_model_dir', type=str, help='Repo name')
parser.add_argument('output_dir_base', type=str, help='Output base folder')