File size: 30,981 Bytes
75cf468
1
2
{"cells":[{"cell_type":"code","execution_count":177,"metadata":{"execution":{"iopub.execute_input":"2023-05-25T14:21:01.420119Z","iopub.status.busy":"2023-05-25T14:21:01.419343Z","iopub.status.idle":"2023-05-25T14:21:01.426167Z","shell.execute_reply":"2023-05-25T14:21:01.425234Z","shell.execute_reply.started":"2023-05-25T14:21:01.420077Z"},"trusted":true},"outputs":[],"source":["#安装目录\n","install_path='/kaggle/working'\n","\n","#优化\n","multi_gpu = 1\n","lowram = 1\n","\n","#保存环境\n","zip_venv = 0\n","\n","#删除脚本重新安装\n","reLoad = 0\n","\n","#更新脚本\n","updata = 0\n","\n","#自动打包训练好的模型\n","zip_output = 1\n","#自动清理\n","clear_output = 1\n","#自动上传抱脸\n","upload = 0\n","hugTokenFile='/kaggle/input/tenkens/hugfacetoken.txt' # 非必填 存放hugfacetoken的文件的路径\n","#类型\n","huggingface_repo_type = \"model\" #dataest\n","#仓库名\n","repo_id=\"sukaka/trained_sd_model\"\n","#上传抱脸的文件夹路径\n","floder_name = 'test'\n","\n","#一键倒入炼丹参数\n","config_file='#/kaggle/input/input-qin/qin.toml'\n","#保留本次炼丹的参数\n","save_config = 0"]},{"cell_type":"code","execution_count":178,"metadata":{"execution":{"iopub.execute_input":"2023-05-25T14:21:01.485567Z","iopub.status.busy":"2023-05-25T14:21:01.485123Z","iopub.status.idle":"2023-05-25T14:21:01.499912Z","shell.execute_reply":"2023-05-25T14:21:01.498203Z","shell.execute_reply.started":"2023-05-25T14:21:01.485530Z"},"trusted":true},"outputs":[],"source":["# Train data path | 设置训练用模型、图片\n","#底膜选择:二次元选择animefull-final-pruned.safetensors,训练三次元选择sd-v1-5.safetensors\n","pretrained_model = \"sd-models/animefull-final-pruned.safetensors\" # base model path | 底模路径\n","is_v2_model = 0 # SD2.0 model | SD2.0模型 2.0模型下 clip_skip 默认无效\n","v_parameterization = 0 # parameterization | 参数化 v2 非512基础分辨率版本必须使用。\n","train_data_dir = \"/kaggle/input/lora-train-picture/Deemo2/Deemo\" # train dataset path | 训练数据集路径\n","reg_data_dir = \"\"\t# reg dataset path | 正则数据集化路径\n","network_weights = \"\" # pretrained weights for LoRA network | 若需要从已有的 LoRA 模型上继续训练,请填写 LoRA 模型路径。\n","training_comment = \"Deemo-sukaka\" # training_comment | 训练介绍,可以写作者名或者使用触发关键词\n","\n","# Output settings | 输出设置\n","output_name = \"Deemo\" # output model name | 模型保存名称\n","save_model_as = \"safetensors\" # model save ext | 模型保存格式 ckpt, pt, safetensors\n","\n","# Train related params | 训练相关参数\n","resolution = \"512,512\" # image resolution w,h. 图片分辨率,宽,高。支持非正方形,但必须是 64 倍数。\n","batch_size = 2 # batch size 一次性训练图片批处理数量,根据显卡质量对应调高。\n","max_train_epoches = 1 # max train epoches | 最大训练 epoch\n","save_every_n_epochs = 1 # save every n epochs | 每 N 个 epoch 保存一次\n","\n","gradient_checkpointing = 0 #梯度检查,开启后可节约显存,但是速度变慢\n","gradient_accumulation_steps = 64 # 梯度累加数量,变相放大batchsize的倍数\n","\n","network_dim = 128 # network dim | 常用 4~128,不是越大越好\n","network_alpha = 64 # network alpha | 常用与 network_dim 相同的值或者采用较小的值,如 network_dim的一半 防止下溢。默认值为 1,使用较小的 alpha 需要提升学习率。\n","\n","train_unet_only = 0 # train U-Net only | 仅训练 U-Net,开启这个会牺牲效果大幅减少显存使用。6G显存可以开启\n","train_text_encoder_only = 0 # train Text Encoder only | 仅训练 文本编码器\n","stop_text_encoder_training = 0 # stop text encoder training | 在第N步时停止训练文本编码器\n","\n","seed = 114514 # reproducable seed | 设置跑测试用的种子,输入一个prompt和这个种子大概率得到训练图。可以用来试触发关键词\n","\n","#noise | 噪声\n","noise_offset = 0 # help allow SD to gen better blacks and whites,(0-1) | 帮助SD更好分辨黑白,推荐概念0.06,画风0.1\n","multires_noise_iterations = 6 #多分辨率噪声扩散次数,推荐6-10,0禁用。\n","multires_noise_discount = 0.1 #多分辨率噪声缩放倍数,推荐0.1-0.3,上面关掉的话禁用。\n","\n","#lycoris组件\n","enable_lycoris = 0 # 开启lycoris\n","conv_dim = 16 #卷积 dim,推荐<32\n","conv_alpha = 1 #卷积 alpha,推荐1或者0.3\n","algo = \"lora\" # algo参数,指定训练lycoris模型种类,包括lora(就是locon)、loha、IA3以及lokr、dylora ,5个可选\n","\n","#dylora组件\n","enable_dylora = 0 # 开启dylora,和lycoris冲突,只能开一个。\n","unit = 4 #分割块数单位,最小1也最慢。一般4、8、12、16这几个选\n","\n","# Learning rate | 学习率\n","lr = \"8.067e-5\"\n","unet_lr = \"8.067e-5\"\n","text_encoder_lr = \"2.689e-5\"\n","lr_scheduler = \"cosine_with_restarts\" # \"linear\", \"cosine\", \"cosine_with_restarts\", \"polynomial\", \"constant\", \"constant_with_warmup\" | PyTorch自带6种动态学习率函数\n","# constant,常量不变, constant_with_warmup 线性增加后保持常量不变, linear 线性增加线性减少, polynomial 线性增加后平滑衰减, cosine 余弦波曲线, cosine_with_restarts 余弦波硬重启,瞬间最大值。\n","# 推荐默认cosine_with_restarts或者polynomial,配合输出多个epoch结果更玄学\n","lr_warmup_steps = 0 # warmup steps | 学习率预热步数,lr_scheduler 为 constant 或 adafactor 时该值需要设为0。仅在 lr_scheduler 为 constant_with_warmup 时需要填写这个值\n","lr_scheduler_num_cycles = 1 # restarts nums | 余弦退火重启次数,仅在 lr_scheduler 为 cosine_with_restarts 时需要填写这个值\n","\n","# 优化器\n","optimizer_type = \"Lion\" #DAdaptation和Lion\n","# 可选优化器\"adaFactor\",\"AdamW\",\"AdamW8bit\",\"Lion\",\"SGDNesterov\",\"SGDNesterov8bit\",\"DAdaptation\"(DAdaptAdam),  \n","# 新增优化器\"Lion8bit\"(速度更快,内存消耗更少)、\"DAdaptAdaGrad\"\"DAdaptAdan\"(北大最新算法,效果待测)、\"DAdaptSGD\"\n","\n","shuffle_caption = 1 # 随机打乱tokens\n","keep_tokens = 5 # keep heading N tokens when shuffling caption tokens | 在随机打乱 tokens 时,保留前 N 个不变。\n","prior_loss_weight = 0 #正则化权重,0-1\n","min_snr_gamma = 5 #最小信噪比伽马值,减少低step时loss值,让学习效果更好。推荐3-5,5对原模型几乎没有太多影响,3会改变最终结果。修改为0禁用。\n","\n","weighted_captions=0 #权重打标,默认识别标签权重,语法同webui基础用法。例如(abc), [abc],(abc:1.23),但是不能在括号内加逗号,否则无法识别。一个文件最多75个tokens。\n","\n","# block weights | 分层训练\n","enable_block_weights=0 #开启分层训练,和lycoris冲突,只能开一个。\n","down_lr_weight=\"1,0.2,1,1,0.2,1,1,0.2,1,1,1,1\" #12层,需要填写12个数字,0-1.也可以使用函数写法,支持sine, cosine, linear, reverse_linear, zeros,参考写法down_lr_weight=cosine+.25 \n","mid_lr_weight=\"1\"  #1层,需要填写1个数字,其他同上。\n","up_lr_weight=\"1,1,1,1,1,1,1,1,1,1,1,1\"   #12层,同上上。\n","block_lr_zero_threshold=0  #如果分层权重不超过这个值,那么直接不训练。默认0。\n","\n","#输出采样图片\n","enable_sample = 0 #1开启出图,0禁用\n","sample_every_n_epochs = 1 #每n个epoch出一次图\n","sample_prompts=\"/kaggle/input/lora-train-picture/Deemo2/test-picture.txt\" #prompt文件路径\n","sample_sampler=\"euler_a\" #采样器 'ddim', 'pndm', 'heun', 'dpmsolver', 'dpmsolver++', 'dpmsingle', 'k_lms', 'k_euler', 'k_euler_a', 'k_dpm_2', 'k_dpm_2_a'\n","\n","#wandb 日志同步\n","wandb_api_key_file=\"/kaggle/input/tenkens/wandb API key.txt\" # wandbAPI KEY,用于登录\n","\n","# 其他设置\n","min_bucket_reso = 256 # arb min resolution | arb 最小分辨率\n","max_bucket_reso = 1024 # arb max resolution | arb 最大分辨率\n","vae_batch_size = 2 #vae批处理大小,2-4\n","clip_skip = 2 # clip skip | 玄学 一般用 2"]},{"cell_type":"code","execution_count":179,"metadata":{"execution":{"iopub.execute_input":"2023-05-25T14:21:01.504592Z","iopub.status.busy":"2023-05-25T14:21:01.501782Z","iopub.status.idle":"2023-05-25T14:21:01.524314Z","shell.execute_reply":"2023-05-25T14:21:01.523309Z","shell.execute_reply.started":"2023-05-25T14:21:01.504564Z"},"trusted":true},"outputs":[],"source":["#一些基础模型下载\n","model_download_urls = [\n","#novelai\n","'https://huggingface.co/datasets/sukaka/sd_models_fp16/resolve/main/animefull-final-pruned.safetensors',\n","#sdv1.5\n","'https://huggingface.co/datasets/sukaka/sd_models_fp16/resolve/main/sd-v1-5.safetensors'\n","]\n","#下载在sd-models/"]},{"cell_type":"code","execution_count":180,"metadata":{"execution":{"iopub.execute_input":"2023-05-25T14:21:01.526308Z","iopub.status.busy":"2023-05-25T14:21:01.525650Z","iopub.status.idle":"2023-05-25T14:21:01.541963Z","shell.execute_reply":"2023-05-25T14:21:01.540968Z","shell.execute_reply.started":"2023-05-25T14:21:01.526257Z"},"trusted":true},"outputs":[],"source":["import shutil\n","import gc\n","import os\n","import re\n","import time\n","import subprocess\n","import multiprocessing\n","import inspect\n","import pkg_resources\n","from pathlib import Path\n","from concurrent.futures import ProcessPoolExecutor\n","os.environ['install_path'] = install_path\n","os.environ['HF_HOME'] = 'huggingface'\n","os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'\n","os.environ[\"PL_TORCH_DISTRIBUTED_BACKEND\"] = \"gloo\""]},{"cell_type":"code","execution_count":181,"metadata":{"execution":{"iopub.execute_input":"2023-05-25T14:21:01.573033Z","iopub.status.busy":"2023-05-25T14:21:01.572724Z","iopub.status.idle":"2023-05-25T14:21:01.606980Z","shell.execute_reply":"2023-05-25T14:21:01.606017Z","shell.execute_reply.started":"2023-05-25T14:21:01.573006Z"},"trusted":true},"outputs":[],"source":["ext_args = []\n","if lowram == 1:\n","    ext_args.append('--lowram')\n","\n","if is_v2_model == 1:\n","    ext_args.append(\"--v2\")\n","    if v_parameterization == 1:\n","        ext_args.append(\"--v_parameterization\")\n","else:\n","    ext_args.append(f\"--clip_skip={clip_skip}\")\n","\n","if train_unet_only == 1:\n","    ext_args.append(\"--network_train_unet_only\")\n","\n","if train_text_encoder_only == 1:\n","    ext_args.append(\"--network_train_text_encoder_only\")\n","\n","if stop_text_encoder_training != 0:\n","    ext_args.append(f\"--stop_text_encoder_training={stop_text_encoder_training}\")\n","\n","if shuffle_caption:\n","    ext_args.append(\"--shuffle_caption\")\n","\n","if weighted_captions:\n","    ext_args.append(\"--weighted_captions\")\n","\n","if gradient_checkpointing == 1:\n","    ext_args.append(\"--gradient_checkpointing\")\n","\n","if gradient_accumulation_steps != 0:\n","    ext_args.append(f\"--gradient_accumulation_steps={gradient_accumulation_steps}\")\n","\n","if noise_offset != 0:\n","    ext_args.append(f\"--noise_offset={noise_offset}\")\n","elif multires_noise_iterations != 0:\n","    ext_args.append(f\"--multires_noise_iterations={multires_noise_iterations}\")\n","    ext_args.append(f\"--multires_noise_discount={multires_noise_discount}\")\n","\n","if enable_block_weights == 1:\n","    enable_dylora = 0\n","    enable_lycoris = 0\n","    ext_args.append(\"--network_args\")\n","    ext_args.append(f\"down_lr_weight={down_lr_weight}\")\n","    ext_args.append(f\"mid_lr_weight={mid_lr_weight}\")\n","    ext_args.append(f\"up_lr_weight={up_lr_weight}\")\n","    ext_args.append(f\"block_lr_zero_threshold={block_lr_zero_threshold}\")\n","    if conv_dim != 0:\n","        ext_args.append(f\"conv_dim={conv_dim}\")\n","        if conv_alpha != 0:\n","            ext_args.append(f\"conv_alpha={conv_alpha}\")\n","\n","if enable_lycoris == 1:\n","    enable_dylora = 0\n","    ext_args.append(\"--network_module=lycoris.kohya\")\n","    ext_args.append(\"--network_args\")\n","    if conv_dim != 0:\n","        ext_args.append(f\"conv_dim={conv_dim}\")\n","        if conv_alpha != 0:\n","            ext_args.append(f\"conv_alpha={conv_alpha}\")\n","    ext_args.append(f\"algo={algo}\")\n","else:\n","    ext_args.append(\"--network_module=networks.lora\")\n","\n","if enable_dylora == 1:\n","    ext_args.append(\"--network_module=networks.dylora\")\n","    ext_args.append(\"--network_args\")\n","    ext_args.append(f\"unit={unit}\")\n","    if conv_dim != 0:\n","        ext_args.append(f\"conv_dim={conv_dim}\")\n","        if conv_alpha != 0:\n","            ext_args.append(f\"conv_alpha={conv_alpha}\")\n","\n","if optimizer_type == \"adafactor\":\n","    ext_args.append(f\"--optimizer_type={optimizer_type}\")\n","    ext_args.append(\"--optimizer_args\")\n","    ext_args.append(\"scale_parameter=True\")\n","    ext_args.append(\"warmup_init=True\")\n","\n","if optimizer_type in [\"DAdaptation\", \"DAdaptAdam\", \"DAdaptAdaGrad\", \"DAdaptAdan\", \"DAdaptSGD\"]:\n","    ext_args.append(f\"--optimizer_type={optimizer_type}\")\n","    ext_args.append(\"--optimizer_args\")\n","    if optimizer_type in [\"DAdaptation\", \"DAdaptAdam\"]:\n","        ext_args.append(\"decouple=True\")\n","        ext_args.append(\"weight_decay=0.01\")\n","    lr = \"1\"\n","    unet_lr = \"1\"\n","    text_encoder_lr = \"1\"\n","\n","if optimizer_type in [\"Lion\", \"Lion8bit\"]:\n","    ext_args.append(f\"--optimizer_type={optimizer_type}\")\n","    ext_args.append(\"--optimizer_args\")\n","    ext_args.append(\"betas=.95,.98\")\n","\n","if optimizer_type == \"AdamW8bit\":\n","    optimizer_type = \"\"\n","    ext_args.append(\"--use_8bit_adam\")\n","\n","if network_weights:\n","    ext_args.append(f\"--network_weights={network_weights}\")\n","\n","if reg_data_dir:\n","    ext_args.append(f\"--reg_data_dir={reg_data_dir}\")\n","    if prior_loss_weight != 0:\n","        ext_args.append(f\"--prior_loss_weight={prior_loss_weight}\")\n","\n","if keep_tokens != 0 :\n","    ext_args.append(f\"--keep_tokens={keep_tokens}\")\n","\n","if min_snr_gamma != 0:\n","    ext_args.append(f\"--min_snr_gamma={min_snr_gamma}\")\n","if Path(wandb_api_key_file).exists():\n","    with open(wandb_api_key_file, encoding=\"utf-8\") as nkfile:\n","        wandb_api_key = nkfile.readline()\n","    if wandb_api_key != '':\n","        ext_args.append(f\"--wandb_api_key={wandb_api_key}\")\n","        ext_args.append(\"--log_with=wandb\")\n","        ext_args.append(f\"--log_tracker_name={output_name}\")\n","\n","if enable_sample == 1:\n","    ext_args.append(f\"--sample_every_n_epochs={sample_every_n_epochs}\")\n","    ext_args.append(f\"--sample_prompts={sample_prompts}\")\n","    ext_args.append(f\"--sample_sampler={sample_sampler}\")"]},{"cell_type":"code","execution_count":182,"metadata":{"execution":{"iopub.execute_input":"2023-05-25T14:21:01.642488Z","iopub.status.busy":"2023-05-25T14:21:01.641770Z","iopub.status.idle":"2023-05-25T14:21:01.742301Z","shell.execute_reply":"2023-05-25T14:21:01.741061Z","shell.execute_reply.started":"2023-05-25T14:21:01.642458Z"},"trusted":true},"outputs":[],"source":["#功能函数,内存优化\n","def libtcmalloc():\n","    if os.path.exists('/kaggle/temp'):\n","        os.chdir('/kaggle')\n","        os.chdir('temp')\n","        os.environ[\"LD_PRELOAD\"] = \"libtcmalloc.so\"\n","        print('内存优化已安装')\n","    else:\n","        os.chdir('/kaggle')\n","        os.makedirs('temp', exist_ok=True)\n","        os.chdir('temp')\n","        os.system('wget -qq  http://launchpadlibrarian.net/367274644/libgoogle-perftools-dev_2.5-2.2ubuntu3_amd64.deb')\n","        os.system('wget -qq  https://launchpad.net/ubuntu/+source/google-perftools/2.5-2.2ubuntu3/+build/14795286/+files/google-perftools_2.5-2.2ubuntu3_all.deb')\n","        os.system('wget -qq  https://launchpad.net/ubuntu/+source/google-perftools/2.5-2.2ubuntu3/+build/14795286/+files/libtcmalloc-minimal4_2.5-2.2ubuntu3_amd64.deb')\n","        os.system('wget -qq  https://launchpad.net/ubuntu/+source/google-perftools/2.5-2.2ubuntu3/+build/14795286/+files/libgoogle-perftools4_2.5-2.2ubuntu3_amd64.deb')\n","        os.system('apt install -qq libunwind8-dev -y > /dev/null 2>&1')\n","        !dpkg -i *.deb\n","        os.environ[\"LD_PRELOAD\"] = \"libtcmalloc.so\"\n","        !rm *.deb\n","        \n","def LoRA_scripts_install():\n","    %cd $install_path\n","    if reLoad == 1:\n","        !rm -rf sd-scripts\n","    if Path(\"lora-scripts\").exists():\n","        if updata == 1:\n","            %cd sd-scripts\n","            !git checkout .\n","            !git pull\n","            print('LoRA-scripts已更新')\n","        else:\n","            print('LoRA-scripts已安装')\n","    else:\n","        print('LoRA-scripts安装中')\n","        #下载kohya-ss的脚本\n","        !git clone https://github.com/kohya-ss/sd-scripts\n","        print('LoRA-scripts已安装')\n","\n","def venv_install():\n","    %cd /opt/conda/envs\n","    if os.path.exists('venv'):\n","        print('环境已安装')\n","    else:\n","        %cd /kaggle/working/\n","        if not os.path.exists('venv.tar.gz'):\n","            print('环境包下载中')\n","            !wget https://huggingface.co/datasets/sukaka/venv_ai_drow/resolve/main/lora_train/lora_train_torch201_cu118_xf20.tar.gz -O venv.tar.gz\n","        print('环境包已下载')\n","        %cd /opt/conda/envs/\n","        !mkdir venv\n","        %cd venv\n","        print('环境安装中')\n","        os.system('apt -y install -qq pigz > /dev/null 2>&1')\n","        !pigz -dc -p 5 /kaggle/working/venv.tar.gz | tar xf -\n","        !source /opt/conda/bin/activate venv\n","        print('环境安装完毕')"]},{"cell_type":"code","execution_count":183,"metadata":{"execution":{"iopub.execute_input":"2023-05-25T14:21:01.745123Z","iopub.status.busy":"2023-05-25T14:21:01.744421Z","iopub.status.idle":"2023-05-25T14:21:01.760374Z","shell.execute_reply":"2023-05-25T14:21:01.759518Z","shell.execute_reply.started":"2023-05-25T14:21:01.745087Z"},"trusted":true},"outputs":[],"source":["def download_links(links, target_folder):\n","    for link in links:\n","        if link.startswith('https://huggingface.co/'):\n","            filename = re.search(r'[^/]+$', link).group(0)\n","            os.system(f'aria2c --console-log-level=error -q -c -x 16 -s 16 -k 1M -d \"{target_folder}\" -o \"{filename}\" \"{link}\"')\n","        else:\n","            os.system(f'aria2c --console-log-level=error -q -c -x 16 -s 16 -k 1M --remote-time -d \"{target_folder}\" \"{link}\"')\n","def download_models():\n","    os.system('apt -y install -qq aria2 > /dev/null 2>&1')\n","    %cd $install_path/sd-scripts\n","    !mkdir sd-models\n","    download_links(model_download_urls, 'sd-models')"]},{"cell_type":"code","execution_count":184,"metadata":{"execution":{"iopub.execute_input":"2023-05-25T14:21:01.762346Z","iopub.status.busy":"2023-05-25T14:21:01.761786Z","iopub.status.idle":"2023-05-25T14:21:01.785176Z","shell.execute_reply":"2023-05-25T14:21:01.784238Z","shell.execute_reply.started":"2023-05-25T14:21:01.762313Z"},"trusted":true},"outputs":[],"source":["def set_cmd(launch_args,ext_args):\n","    cmd = f\"\"\"conda run -n venv --no-capture-output accelerate launch {' '.join(launch_args)} \"train_network.py\" \\\n","    --enable_bucket \\\n","    --pretrained_model_name_or_path={pretrained_model} \\\n","    --train_data_dir={train_data_dir} \\\n","    --output_dir=\"/kaggle/working/output\" \\\n","    --logging_dir=\"/kaggle/working/logs\" \\\n","    --log_prefix={output_name} \\\n","    --resolution={resolution} \\\n","    --max_train_epochs={max_train_epoches} \\\n","    --learning_rate={lr} \\\n","    --unet_lr={unet_lr} \\\n","    --text_encoder_lr={text_encoder_lr} \\\n","    --lr_scheduler={lr_scheduler} \\\n","    --lr_warmup_steps={lr_warmup_steps} \\\n","    --network_dim={network_dim} \\\n","    --network_alpha={network_alpha} \\\n","    --output_name={output_name} \\\n","    --train_batch_size={batch_size} \\\n","    --save_every_n_epochs={save_every_n_epochs} \\\n","    --mixed_precision=\"fp16\" \\\n","    --save_precision=\"fp16\" \\\n","    --seed=\"1337\" \\\n","    --prior_loss_weight=1 \\\n","    --max_token_length=225 \\\n","    --caption_extension=\".txt\" \\\n","    --save_model_as={save_model_as} \\\n","    --min_bucket_reso={min_bucket_reso} \\\n","    --max_bucket_reso={max_bucket_reso} \\\n","    --training_comment={training_comment} \\\n","    --xformers {' '.join(ext_args)} \"\"\"\n","    os.system(cmd)\n","    \n","def train_start():\n","    %cd /kaggle/working\n","    !mkdir output\n","    !mkdir logs\n","    %cd $install_path/sd-scripts\n","    \n","    launch_args = []\n","    \n","    if multi_gpu == 1:\n","        launch_args.append('--multi_gpu')\n","        \n","    launch_args.append('--num_cpu_threads_per_process=2')\n","        \n","    if Path(config_file).is_file():\n","        cmd = f\"\"\"conda run -n venv --no-capture-output accelerate launch {' '.join(launch_args)} \"train_network.py\" \\\n","        --config_file={config_file}\"\"\"\n","        os.system(cmd)\n","    else:\n","        if save_config == 1:\n","            ext_args.append(\"--output_config\")\n","            ext_args.append(f\"--config_file=/kaggle/working/output/{output_name}.toml\")\n","            set_cmd(launch_args,ext_args)\n","            ext_args.remove(\"--output_config\")\n","            ext_args.remove(f\"--config_file=/kaggle/working/output/{output_name}.toml\")\n","        set_cmd(launch_args,ext_args)"]},{"cell_type":"code","execution_count":185,"metadata":{"execution":{"iopub.execute_input":"2023-05-25T14:21:01.786961Z","iopub.status.busy":"2023-05-25T14:21:01.786540Z","iopub.status.idle":"2023-05-25T14:21:01.801703Z","shell.execute_reply":"2023-05-25T14:21:01.800818Z","shell.execute_reply.started":"2023-05-25T14:21:01.786928Z"},"trusted":true},"outputs":[],"source":["def main():\n","    !apt-get update\n","    startTicks = time.time()\n","    with ProcessPoolExecutor() as executor:\n","        futures = [executor.submit(func) for func in [LoRA_scripts_install, venv_install,libtcmalloc]]\n","        for future in futures:\n","            future.result()\n","    libtcmalloc()\n","    download_models()\n","    startTicks = time.time()\n","    train_start()"]},{"cell_type":"code","execution_count":189,"metadata":{"execution":{"iopub.execute_input":"2023-05-25T14:24:24.093177Z","iopub.status.busy":"2023-05-25T14:24:24.092723Z","iopub.status.idle":"2023-05-25T14:24:24.132431Z","shell.execute_reply":"2023-05-25T14:24:24.131099Z","shell.execute_reply.started":"2023-05-25T14:24:24.093137Z"},"trusted":true},"outputs":[],"source":["from pathlib import Path\n","extensions = [\".safetensors\", \".pt\", \".ckpt\" ,\".png\" ,\".toml\", '.tar.gz' ,'.txt']\n","\n","def create_tar_gz(input_folder, output_file):\n","    # 切换到 input_folder 的父文件夹\n","    os.chdir(os.path.dirname(input_folder))\n","    # 使用相对路径来指定要压缩的文件夹\n","    input_folder = os.path.basename(input_folder)\n","    subprocess.run(['tar', '--use-compress-program=pigz', '-p 4', '-cf', output_file, input_folder])\n","\n","\n","def clear_directory(folder_path):\n","    if not os.path.exists(folder_path):\n","        return\n","    for filename in os.listdir(folder_path):\n","        file_path = os.path.join(folder_path, filename)\n","        if os.path.isfile(file_path):\n","            os.remove(file_path)\n","        elif os.path.isdir(file_path):\n","            shutil.rmtree(file_path)\n","\n","def hugface_upload(input_folder):\n","    if Path(hugTokenFile).exists():\n","        with open(hugTokenFile, encoding=\"utf-8\") as nkfile:\n","            hugToken = nkfile.readline()\n","    if upload == 1 and hugToken != '':\n","        from huggingface_hub import login\n","        # 使用您的 Hugging Face 访问令牌登录\n","        login(token=hugToken)\n","        from huggingface_hub import HfApi\n","        # 实例化 HfApi 类\n","        api = HfApi()\n","        print(\"HfApi 类已实例化\")\n","\n","        # 使用 upload_file() 函数上传文件\n","        print(\"开始上传文件...\")\n","        \n","        def upload_file(file):\n","            if not os.path.exists(file):\n","                print(f\"Skipping non-local file: '{file}'\")\n","                return\n","            file_name = os.path.basename(file)\n","            response = api.upload_file(\n","                path_or_fileobj=file,\n","                path_in_repo=f\"{floder_name}/{file_name}\",\n","                repo_id=repo_id,\n","                repo_type=huggingface_repo_type\n","            )\n","            print(f\"文件 {file} 上传完成\")\n","            print(f\"响应: {response}\")\n","\n","        files = [str(file) for ext in extensions for file in Path(input_folder).glob(f\"*{ext}\")]\n","        for file in files:\n","            upload_file(file)\n","\n","\n","def zip_clear():\n","    if zip_output == 1:\n","        create_tar_gz('/kaggle/working/output/', '/kaggle/working/模型.tar.gz')\n","        create_tar_gz('/kaggle/working/logs', '/kaggle/working/logs.tar.gz')\n","        print('模型已压缩到output')\n","    if clear_output == 1:\n","        clear_directory('/kaggle/working/output')\n","        clear_directory('/kaggle/working/logs')\n","        print('清理完毕')\n","\n","def after_train():\n","    if enable_sample == 1:\n","        shutil.copy2(f'{sample_prompts}', '/kaggle/working/output/sample/sample_prompts.txt')\n","    create_tar_gz('/kaggle/working/logs', '/kaggle/working/output/logs.tar.gz')\n","    hugface_upload(f'{install_path}/output')\n","    if zip_venv == 1:\n","        !pip install conda-pack\n","        !rm -rf /kaggle/working/venv.tar.gz\n","        !conda pack -n venv -o /kaggle/working/venv.tar.gz --compress-level 0\n","    zip_clear()"]},{"cell_type":"code","execution_count":187,"metadata":{"execution":{"iopub.execute_input":"2023-05-25T14:21:01.846448Z","iopub.status.busy":"2023-05-25T14:21:01.846164Z","iopub.status.idle":"2023-05-25T14:21:14.890444Z","shell.execute_reply":"2023-05-25T14:21:14.889046Z","shell.execute_reply.started":"2023-05-25T14:21:01.846424Z"},"trusted":true},"outputs":[{"name":"stdout","output_type":"stream","text":["/opt/conda/envs/kaggle/working\n","LoRA-scripts安装中\n","\n","环境已安装\n","内存优化已安装\n","fatal: destination path 'sd-scripts' already exists and is not an empty directory.\n","LoRA-scripts已安装\n","内存优化已安装\n","/kaggle/working/sd-scripts\n","mkdir: cannot create directory ‘sd-models’: File exists\n","/kaggle/working\n","mkdir: cannot create directory ‘output’: File exists\n","mkdir: cannot create directory ‘logs’: File exists\n","/kaggle/working/sd-scripts\n"]},{"name":"stderr","output_type":"stream","text":["Fatal Python error: init_import_site: Failed to import the site module\n","Python runtime state: initialized\n","Traceback (most recent call last):\n","  File \"/opt/conda/lib/python3.10/site.py\", line 617, in <module>\n","    main()\n","  File \"/opt/conda/lib/python3.10/site.py\", line 610, in main\n","    execsitecustomize()\n","  File \"/opt/conda/lib/python3.10/site.py\", line 549, in execsitecustomize\n","    import sitecustomize\n","  File \"/root/.local/lib/python3.10/site-packages/sitecustomize.py\", line 3, in <module>\n","    from log import Log\n","  File \"/root/.local/lib/python3.10/site-packages/log.py\", line 4, in <module>\n","    import google.auth\n","  File \"/opt/conda/lib/python3.10/site-packages/google/auth/__init__.py\", line 20, in <module>\n","    from google.auth._default import default, load_credentials_from_file\n","  File \"/opt/conda/lib/python3.10/site-packages/google/auth/_default.py\", line 30, in <module>\n","    import google.auth.transport._http_client\n","  File \"/opt/conda/lib/python3.10/site-packages/google/auth/transport/__init__.py\", line 30, in <module>\n","    from six.moves import http_client\n","  File \"<frozen importlib._bootstrap>\", line 1075, in _handle_fromlist\n","  File \"/opt/conda/lib/python3.10/site-packages/six.py\", line 97, in __get__\n","    result = self._resolve()\n","  File \"/opt/conda/lib/python3.10/site-packages/six.py\", line 120, in _resolve\n","    return _import_module(self.mod)\n","  File \"/opt/conda/lib/python3.10/site-packages/six.py\", line 87, in _import_module\n","    __import__(name)\n","  File \"/opt/conda/lib/python3.10/http/client.py\", line 71, in <module>\n","    import email.parser\n","  File \"/opt/conda/lib/python3.10/email/parser.py\", line 12, in <module>\n","    from email.feedparser import FeedParser, BytesFeedParser\n","  File \"/opt/conda/lib/python3.10/email/feedparser.py\", line 27, in <module>\n","    from email._policybase import compat32\n","  File \"/opt/conda/lib/python3.10/email/_policybase.py\", line 7, in <module>\n","    from email import header\n","  File \"/opt/conda/lib/python3.10/email/header.py\", line 14, in <module>\n","    import binascii\n","KeyboardInterrupt\n","\n","CondaError: KeyboardInterrupt\n","\n"]}],"source":["main()"]},{"cell_type":"code","execution_count":190,"metadata":{"execution":{"iopub.execute_input":"2023-05-25T14:24:27.361221Z","iopub.status.busy":"2023-05-25T14:24:27.360159Z","iopub.status.idle":"2023-05-25T14:24:27.564700Z","shell.execute_reply":"2023-05-25T14:24:27.563605Z","shell.execute_reply.started":"2023-05-25T14:24:27.361168Z"},"trusted":true},"outputs":[{"name":"stdout","output_type":"stream","text":["Token will not been saved to git credential helper. Pass `add_to_git_credential=True` if you want to set the git credential as well.\n","Token is valid.\n","Your token has been saved to huggingface/token\n","Login successful\n","HfApi 类已实例化\n","开始上传文件...\n","模型已压缩到output\n","Skipping specified file: '/kaggle/working/output/sample'\n","清理完毕\n"]},{"name":"stderr","output_type":"stream","text":["tar: invalid option -- ' '\n","Try 'tar --help' or 'tar --usage' for more information.\n","tar: invalid option -- ' '\n","Try 'tar --help' or 'tar --usage' for more information.\n","tar: invalid option -- ' '\n","Try 'tar --help' or 'tar --usage' for more information.\n"]}],"source":["#训练完毕,手动执行。进行打包和上传\n","after_train()"]}],"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"codemirror_mode":{"name":"ipython","version":3},"file_extension":".py","mimetype":"text/x-python","name":"python","nbconvert_exporter":"python","pygments_lexer":"ipython3","version":"3.10.10"}},"nbformat":4,"nbformat_minor":4}