diff --git "a/2512.jsonl" "b/2512.jsonl" new file mode 100644--- /dev/null +++ "b/2512.jsonl" @@ -0,0 +1,505 @@ +{"seq_id":"23349075782","text":"import RPi.GPIO as GPIO\nimport time\nimport math\n\nGPIO.setwarnings(False)\nGPIO.setmode(GPIO.BOARD)\n\nmyStep = .1\n\n\n\nGPIO.setup(12,GPIO.OUT)\nservo0 = GPIO.PWM(12,50)\nservo0.start(0)\n\ninput0 = 0\n\n\ndef cosineMap(pos):\n mappedPos = math.cos(pos)\n return mappedPos\n\ndef myMapValues(variable,oldLow,oldHigh,newLow,newHigh):\n variable = (variable - oldLow) / (oldHigh - oldLow) * (newHigh - newLow) + newLow\n return variable\n \n\n\nwhile True:\n output0 = cosineMap(input0 + myStep)\n \n \n desiredLow=0\n desiredHigh=180\n output0 = myMapValues(output0, -1,1,desiredLow,desiredHigh)\n #print(\"Post-Map output: \" + str(output0))\n \n \n \n servoWriteOutput0 = 2+(output0/18)\n #print(\"servoWriteOutput0: \" + str(servoWriteOutput0))\n \n \n servo0.ChangeDutyCycle(servoWriteOutput0)\n \n \n \n time.sleep(.05)\n servo0.ChangeDutyCycle(0)\n \n \n \n \n input0 = input0 + myStep\n \n \n \n \n \n\n","repo_name":"glenert41/ANTLA","sub_path":"1ServoSineTestingPython.py","file_name":"1ServoSineTestingPython.py","file_ext":"py","file_size_in_byte":951,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"85"} +{"seq_id":"27225909262","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# # import required library\n\n# In[1]:\n\n\n# Import numpy, pandas for data manipulation\nimport numpy as np\nimport pandas as pd\n\n# Import matplotlib, seaborn for visualization\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport warnings\nwarnings.filterwarnings('ignore')\n\n\n# In[2]:\n\n\n# Import the data\nweather_data = pd.read_csv('weather.csv')\nweather_data.head()\n\n\n# In[8]:\n\n\nrain_df = weather_data[['Date','Rainfall']]\nrain_df.head()\n\n\n# In[9]:\n\n\nrain_df.shape\n\n\n# In[10]:\n\n\nrain_df.info()\n\n\n# **Using 50 values**\n\n# In[15]:\n\n\nrain_df = rain_df.loc[:49]\nrain_df.head()\n\n\n# In[16]:\n\n\nrain_df.shape\n\n\n# In[17]:\n\n\n# Convert the time column into datetime\nrain_df['Date'] = pd.to_datetime(rain_df['Date'])\nrain_df['Date'].head()\n\n\n# In[18]:\n\n\nrain_df.info()\n\n\n# In[24]:\n\n\n# fill the empty row\nrain_df = rain_df.fillna(rain_df['Rainfall'].mean())\nrain_df.head()\n\n\n# ### Dataset Explanation\n\n# In[27]:\n\n\nrain_df.describe()\n\n\n# In[29]:\n\n\n# Output the maximum and minimum rain date\nprint(rain_df.loc[rain_df[\"Rainfall\"] == rain_df[\"Rainfall\"].max()])\nprint(rain_df.loc[rain_df[\"Rainfall\"] == rain_df[\"Rainfall\"].min()])\n\n\n# In[30]:\n\n\n# Reset the index \nrain_df.set_index(\"Date\", inplace=True)\n\n\n# ### Data Visualization\n\n# In[32]:\n\n\n# Plot the daily temperature change \nplt.figure(figsize=(16,10), dpi=100)\nplt.plot(rain_df.index, rain_df.Rainfall, color='tab:red')\nplt.gca().set(title=\"Daily Rain\", xlabel='Date', ylabel=\"rain value\")\nplt.show()\n\n\n# In[35]:\n\n\n# Apply the Moving Average function by a subset of size 10 days.\nrain_df_mean = rain_df.Rainfall.rolling(window=10).mean()\nrain_df_mean.plot(figsize=(16,10))\nplt.show()\n\n\n# In[37]:\n\n\nfrom statsmodels.tsa.seasonal import seasonal_decompose\n\n# Additive Decomposition\nresult_add = seasonal_decompose(rain_df.Rainfall, model='additive', extrapolate_trend=0)\n\n# Plot\nplt.rcParams.update({'figure.figsize': (10,10)})\nresult_add.plot().suptitle('Additive Decomposition', fontsize=22)\nplt.show()\n\n\n# ### Baseline Model\n\n# In[38]:\n\n\n# Shift the current rain to the next day. \npredicted_df = rain_df[\"Rainfall\"].to_frame().shift(1).rename(columns = {\"Rainfall\": \"rain_pred\" })\nactual_df = rain_df[\"Rainfall\"].to_frame().rename(columns = {\"Rainfall\": \"rain_actual\" })\n\n# Concatenate the actual and predicted rain\none_step_df = pd.concat([actual_df,predicted_df],axis=1)\n\n# Select from the second row, because there is no prediction for today due to shifting.\none_step_df = one_step_df[1:]\none_step_df.head(10)\n\n\n# > Here you can the we have two column one is our **actual rain** column and othe is **predicted rain** column that we use next model \n\n# We could validate how well our model is by looking at the Root Mean Squared Error(RMSE) between the predicted and actual rain\n\n# In[41]:\n\n\nfrom sklearn.metrics import mean_squared_error as MSE\nfrom math import sqrt\n\n# Calculate the RMSE\nrain_pred_err = MSE(one_step_df.rain_actual, one_step_df.rain_pred, squared=False)\nprint(\"The RMSE is\",rain_pred_err)\n\n\n# > Our RMSE value is 4.002 is arround 4 that are pretty good for model.\n\n# ## Using SARIMA model\n\n# ### Parameter Selection\n# #### Grid Search\n# We are going to apply one of the most commonly used method for time-series forecasting, known as SARIMA, which stands for Seasonal Autoregressive Integrated Moving Average. SARIMA models are denoted with the notation SARIMA(p,d,q)(P,D,Q,s). These three parameters account for seasonality, trend, and noise in data:\n# \n# We will use a “grid search” to iteratively explore different combinations of parameters. For each combination of parameters, we fit a new seasonal SARIMA model with the SARIMAX() function from the statsmodels module and assess its overall quality.\n\n# In[42]:\n\n\nimport itertools\n\n# Define the p, d and q parameters to take any value between 0 and 2\np = d = q = range(0, 2)\n\n# Generate all different combinations of p, q and q triplets\npdq = list(itertools.product(p, d, q))\n\n# Generate all different combinations of seasonal p, q and q triplets\nseasonal_pdq = [(x[0], x[1], x[2], 12) for x in list(itertools.product(p, d, q))]\n\nprint('Examples of parameter combinations for Seasonal ARIMA...')\nprint('SARIMAX: {} x {}'.format(pdq[1], seasonal_pdq[1]))\nprint('SARIMAX: {} x {}'.format(pdq[1], seasonal_pdq[2]))\nprint('SARIMAX: {} x {}'.format(pdq[2], seasonal_pdq[3]))\nprint('SARIMAX: {} x {}'.format(pdq[2], seasonal_pdq[4]))\n\n\n# In[43]:\n\n\nfor param in pdq:\n for param_seasonal in seasonal_pdq:\n try:\n mod = sm.tsa.statespace.SARIMAX(one_step_df.rain_actual,\n order=param,\n seasonal_order=param_seasonal,\n enforce_stationarity=False,\n enforce_invertibility=False)\n\n results = mod.fit()\n\n print('SARIMA{}x{}12 - AIC:{}'.format(param, param_seasonal, results.aic))\n except:\n continue\n\n\n# ### Fitting the Model\n\n# In[47]:\n\n\nimport warnings\nwarnings.filterwarnings(\"ignore\") # specify to ignore warning messages\n# Import the statsmodels library for using SARIMAX model\nimport statsmodels.api as sm\n\n# Fit the SARIMAX model using optimal parameters\nmod = sm.tsa.statespace.SARIMAX(one_step_df.rain_actual,\n order=(1,1,1),\n seasonal_order=(1,1,1,12),\n enforce_stationarity=False,\n enforce_invertibility=False)\n\n\n# In[48]:\n\n\nresults = mod.fit()\n\n\n# In[49]:\n\n\nresults.summary()\n\n\n# **Predictions**\n\n# In[51]:\n\n\npred = results.predict(start=0,end=49)[1:]\npred\n\n\n# In[52]:\n\n\npred = results.get_prediction(start=0,end = 49, dynamic=False)\npred_ci = pred.conf_int()\n\n\n# In[53]:\n\n\npred_ci.head()\n\n\n# In[55]:\n\n\nprint(pred)\n\n\n# In[58]:\n\n\nax = one_step_df.rain_actual.plot(label='observed',figsize=(16,10))\nax.set_xlabel('Date')\nax.set_ylabel('value')\nplt.ylim([0,2.0])\nplt.legend()\nplt.show()\n\n\n# ### Forecast Diagnostic\n# It is also useful to quantify the accuracy of our forecasts. We will use the MSE (Mean Squared Error), in which for each predicted value, we compute its distance to the true value and square the result\n\n# In[65]:\n\n\ny_forecasted = pred.predicted_mean[:49]\ny_truth = one_step_df.rain_actual\nprint(y_forecasted.shape)\nprint(y_truth.shape)\n# Compute the mean square error\nmse = MSE(y_truth, y_forecasted, squared=True)\nprint('The Mean Squared Error of our forecasts is {}'.format(round(mse, 2)))\n\n\n# Amazziingggg! Our forecast model forecasts the rain with only an error of 25.85. \n# \n# In the weather forecast field, the prediction error of 2.19 degrees seems promising and sufficient, as there are many other factors that contribute to the change in rain, including but not limited to the wind speed, the air pressure, etc.\n\n# ### Validating the Dynamic Forecast\n\n# In this case, we only use information from the time series up to a certain point, and after that, forecasts are generated using values from previous forecasted time points.\n# \n\n# In[66]:\n\n\npred_dynamic = results.get_prediction(start=0,end = 49, dynamic=True, full_results=True)\npred_dynamic_ci = pred_dynamic.conf_int()\n\n\n# In[67]:\n\n\npred_dynamic_ci.head()\n\n\n# Once again, we plot the real and forecasted values of the average daily rain to assess how well we did:\n\n# In[71]:\n\n\nax = one_step_df.rain_actual.plot(label='observed', figsize=(15, 11))\npred_dynamic.predicted_mean.plot(label='Dynamic Forecast', ax=ax)\n\nax.fill_between(pred_dynamic_ci.index,\n pred_dynamic_ci.iloc[:, 0],\n pred_dynamic_ci.iloc[:, 1], color='k', alpha=.25)\n\n\nax.set_xlabel('Date')\nax.set_ylabel('Temperature (in Celsius)')\nplt.ylim([0,2.0])\nplt.legend()\nplt.show()\n\n\n# > In this case, the model seems to predict the rain inaccurately, with major fluctuations between the true value and the predicted value.\n\n# ### Forecast Diagnostic\n\n# In[73]:\n\n\n# Extract the predicted and true values of our time series\ny_forecasted = pred_dynamic.predicted_mean[:49]\ny_truth = one_step_df.rain_actual\n\n# Compute the mean square error\nmse = sqrt(MSE(y_truth, y_forecasted).mean())\nprint('The Root Mean Squared Error of our forecasts is {}'.format(round(mse, 2)))\n\n\n# The **predicted** values obtained from the dynamic forecasts yield an MSE of 3.68. This is significantly higher than the one-step ahead, which is to be expected given that we are relying on less historical data from the time series.\n\n# # Conclusion\n\n# I described how to implement a seasonal SARIMA model in Python. I made extensive use of the pandas and statsmodels libraries and showed how to run model diagnostics, as well as how to produce forecasts of the Rain.\n\n# Recall that in the assumption I made in the section 2.2 Baseline Model, I could even reinforce our assumption and continue our belief that the rainfall today depends on the rainfall yesterday, the rainfall yesterday depends on the day before yesterday, and so on. \n# \n# It is the best so far to use the history up to the point that we would like to make **predictions** on. Especially it holds for weather forecasting, where the rainfall today does not change much from yesterday, and the transition to another season signaling through the rainfall should gradually occur, unless there is any disastrous factors such as storm, drought, etc.\n","repo_name":"shreejitverma/Data-Scientist","sub_path":"Time Series Analysis/Weather Forecasting using SRIMAX Model/weather prediction.py","file_name":"weather prediction.py","file_ext":"py","file_size_in_byte":9365,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"85"} +{"seq_id":"28692992124","text":"import argparse\nimport hashlib\nimport itertools\nimport json\nimport logging\nimport math\nimport uuid\nimport warnings\nfrom os import environ, listdir, makedirs\nfrom os.path import basename, join\nfrom pathlib import Path\nfrom typing import List\n\nimport datasets\nimport numpy as np\nimport torch\nimport torch.nn.functional as F\nimport torch.utils.checkpoint\nimport transformers\nfrom accelerate import Accelerator\nfrom accelerate.logging import get_logger\nfrom accelerate.utils import ProjectConfiguration, set_seed\nfrom huggingface_hub import create_repo, upload_folder\nfrom PIL import Image\nfrom torch import dtype\nfrom torch.nn import Module\nfrom torch.utils.data import Dataset\nfrom torchvision import transforms\nfrom tqdm.auto import tqdm\nfrom transformers import AutoTokenizer, PretrainedConfig\n\nimport diffusers\nfrom diffusers import (\n AutoencoderKL,\n DDPMScheduler,\n DiffusionPipeline,\n DPMSolverMultistepScheduler,\n UNet2DConditionModel,\n)\nfrom diffusers.optimization import get_scheduler\nfrom diffusers.utils import check_min_version, is_wandb_available\nfrom diffusers.utils.import_utils import is_xformers_available\n\n\nif is_wandb_available():\n import wandb\n\n# Will error if the minimal version of diffusers is not installed. Remove at your own risks.\ncheck_min_version(\"0.13.0.dev0\")\n\nlogger = get_logger(__name__)\n\n\ndef log_validation_images_to_tracker(\n images: List[np.array], label: str, validation_prompt: str, accelerator: Accelerator, epoch: int\n):\n logger.info(f\"Logging images to tracker for validation prompt: {validation_prompt}.\")\n\n for tracker in accelerator.trackers:\n if tracker.name == \"tensorboard\":\n np_images = np.stack([np.asarray(img) for img in images])\n tracker.writer.add_images(\"validation\", np_images, epoch, dataformats=\"NHWC\")\n if tracker.name == \"wandb\":\n tracker.log(\n {\n \"validation\": [\n wandb.Image(image, caption=f\"{label}_{epoch}_{i}: {validation_prompt}\")\n for i, image in enumerate(images)\n ]\n }\n )\n\n\n# TODO: Add `prompt_embeds` and `negative_prompt_embeds` parameters to the function when `pre_compute_text_embeddings`\n# argument is implemented.\ndef generate_validation_images(\n text_encoder: Module,\n tokenizer: Module,\n unet: Module,\n vae: Module,\n arguments: argparse.Namespace,\n accelerator: Accelerator,\n weight_dtype: dtype,\n):\n logger.info(\"Running validation images.\")\n\n pipeline_args = {}\n\n if text_encoder is not None:\n pipeline_args[\"text_encoder\"] = accelerator.unwrap_model(text_encoder)\n\n if vae is not None:\n pipeline_args[\"vae\"] = vae\n\n # create pipeline (note: unet and vae are loaded again in float32)\n pipeline = DiffusionPipeline.from_pretrained(\n arguments.pretrained_model_name_or_path,\n tokenizer=tokenizer,\n unet=accelerator.unwrap_model(unet),\n revision=arguments.revision,\n torch_dtype=weight_dtype,\n **pipeline_args,\n )\n\n # We train on the simplified learning objective. If we were previously predicting a variance, we need the\n # scheduler to ignore it\n scheduler_args = {}\n\n if \"variance_type\" in pipeline.scheduler.config:\n variance_type = pipeline.scheduler.config.variance_type\n\n if variance_type in [\"learned\", \"learned_range\"]:\n variance_type = \"fixed_small\"\n\n scheduler_args[\"variance_type\"] = variance_type\n\n pipeline.scheduler = DPMSolverMultistepScheduler.from_config(pipeline.scheduler.config, **scheduler_args)\n pipeline = pipeline.to(accelerator.device)\n pipeline.set_progress_bar_config(disable=True)\n\n generator = (\n None if arguments.seed is None else torch.Generator(device=accelerator.device).manual_seed(arguments.seed)\n )\n\n images_sets = []\n for vp, nvi, vnp, vis, vgs in zip(\n arguments.validation_prompt,\n arguments.validation_number_images,\n arguments.validation_negative_prompt,\n arguments.validation_inference_steps,\n arguments.validation_guidance_scale,\n ):\n images = []\n if vp is not None:\n logger.info(\n f\"Generating {nvi} images with prompt: '{vp}', negative prompt: '{vnp}', inference steps: {vis}, \"\n f\"guidance scale: {vgs}.\"\n )\n\n pipeline_args = {\"prompt\": vp, \"negative_prompt\": vnp, \"num_inference_steps\": vis, \"guidance_scale\": vgs}\n\n # run inference\n # TODO: it would be good to measure whether it's faster to run inference on all images at once, one at a\n # time or in small batches\n for _ in range(nvi):\n with torch.autocast(\"cuda\"):\n image = pipeline(**pipeline_args, num_images_per_prompt=1, generator=generator).images[0]\n images.append(image)\n\n images_sets.append(images)\n\n del pipeline\n if torch.cuda.is_available():\n torch.cuda.empty_cache()\n\n return images_sets\n\n\ndef import_model_class_from_model_name_or_path(pretrained_model_name_or_path: str, revision: str):\n text_encoder_config = PretrainedConfig.from_pretrained(\n pretrained_model_name_or_path,\n subfolder=\"text_encoder\",\n revision=revision,\n )\n model_class = text_encoder_config.architectures[0]\n\n if model_class == \"CLIPTextModel\":\n from transformers import CLIPTextModel\n\n return CLIPTextModel\n elif model_class == \"RobertaSeriesModelWithTransformation\":\n from diffusers.pipelines.alt_diffusion.modeling_roberta_series import RobertaSeriesModelWithTransformation\n\n return RobertaSeriesModelWithTransformation\n else:\n raise ValueError(f\"{model_class} is not supported.\")\n\n\ndef parse_args(input_args=None):\n parser = argparse.ArgumentParser(description=\"Simple example of a training script.\")\n parser.add_argument(\n \"--pretrained_model_name_or_path\",\n type=str,\n default=None,\n required=True,\n help=\"Path to pretrained model or model identifier from huggingface.co/models.\",\n )\n parser.add_argument(\n \"--revision\",\n type=str,\n default=None,\n required=False,\n help=\"Revision of pretrained model identifier from huggingface.co/models.\",\n )\n parser.add_argument(\n \"--tokenizer_name\",\n type=str,\n default=None,\n help=\"Pretrained tokenizer name or path if not the same as model_name\",\n )\n parser.add_argument(\n \"--instance_data_dir\",\n type=str,\n default=None,\n required=False,\n help=\"A folder containing the training data of instance images.\",\n )\n parser.add_argument(\n \"--class_data_dir\",\n type=str,\n default=None,\n required=False,\n help=\"A folder containing the training data of class images.\",\n )\n parser.add_argument(\n \"--instance_prompt\",\n type=str,\n default=None,\n required=False,\n help=\"The prompt with identifier specifying the instance\",\n )\n parser.add_argument(\n \"--class_prompt\",\n type=str,\n default=None,\n help=\"The prompt to specify images in the same class as provided instance images.\",\n )\n parser.add_argument(\n \"--with_prior_preservation\",\n default=False,\n action=\"store_true\",\n help=\"Flag to add prior preservation loss.\",\n )\n parser.add_argument(\"--prior_loss_weight\", type=float, default=1.0, help=\"The weight of prior preservation loss.\")\n parser.add_argument(\n \"--num_class_images\",\n type=int,\n default=100,\n help=(\n \"Minimal class images for prior preservation loss. If there are not enough images already present in\"\n \" class_data_dir, additional images will be sampled with class_prompt.\"\n ),\n )\n parser.add_argument(\n \"--output_dir\",\n type=str,\n default=\"text-inversion-model\",\n help=\"The output directory where the model predictions and checkpoints will be written.\",\n )\n parser.add_argument(\"--seed\", type=int, default=None, help=\"A seed for reproducible training.\")\n parser.add_argument(\n \"--resolution\",\n type=int,\n default=512,\n help=(\n \"The resolution for input images, all the images in the train/validation dataset will be resized to this\"\n \" resolution\"\n ),\n )\n parser.add_argument(\n \"--center_crop\",\n default=False,\n action=\"store_true\",\n help=(\n \"Whether to center crop the input images to the resolution. If not set, the images will be randomly\"\n \" cropped. The images will be resized to the resolution first before cropping.\"\n ),\n )\n parser.add_argument(\"--train_text_encoder\", action=\"store_true\", help=\"Whether to train the text encoder\")\n parser.add_argument(\n \"--train_batch_size\", type=int, default=4, help=\"Batch size (per device) for the training dataloader.\"\n )\n parser.add_argument(\n \"--sample_batch_size\", type=int, default=4, help=\"Batch size (per device) for sampling images.\"\n )\n parser.add_argument(\"--num_train_epochs\", type=int, default=1)\n parser.add_argument(\n \"--max_train_steps\",\n type=int,\n default=None,\n help=\"Total number of training steps to perform. If provided, overrides num_train_epochs.\",\n )\n parser.add_argument(\n \"--checkpointing_steps\",\n type=int,\n default=500,\n help=(\n \"Save a checkpoint of the training state every X updates. These checkpoints can be used both as final\"\n \" checkpoints in case they are better than the last checkpoint, and are also suitable for resuming\"\n \" training using `--resume_from_checkpoint`.\"\n ),\n )\n parser.add_argument(\n \"--checkpoints_total_limit\",\n type=int,\n default=None,\n help=(\n \"Max number of checkpoints to store. Passed as `total_limit` to the `Accelerator` `ProjectConfiguration`.\"\n \" See Accelerator::save_state https://huggingface.co/docs/accelerate/package_reference/accelerator#accelerate.Accelerator.save_state\"\n \" for more docs\"\n ),\n )\n parser.add_argument(\n \"--resume_from_checkpoint\",\n type=str,\n default=None,\n help=(\n \"Whether training should be resumed from a previous checkpoint. Use a path saved by\"\n ' `--checkpointing_steps`, or `\"latest\"` to automatically select the last available checkpoint.'\n ),\n )\n parser.add_argument(\n \"--gradient_accumulation_steps\",\n type=int,\n default=1,\n help=\"Number of updates steps to accumulate before performing a backward/update pass.\",\n )\n parser.add_argument(\n \"--gradient_checkpointing\",\n action=\"store_true\",\n help=\"Whether or not to use gradient checkpointing to save memory at the expense of slower backward pass.\",\n )\n parser.add_argument(\n \"--learning_rate\",\n type=float,\n default=5e-6,\n help=\"Initial learning rate (after the potential warmup period) to use.\",\n )\n parser.add_argument(\n \"--scale_lr\",\n action=\"store_true\",\n default=False,\n help=\"Scale the learning rate by the number of GPUs, gradient accumulation steps, and batch size.\",\n )\n parser.add_argument(\n \"--lr_scheduler\",\n type=str,\n default=\"constant\",\n help=(\n 'The scheduler type to use. Choose between [\"linear\", \"cosine\", \"cosine_with_restarts\", \"polynomial\",'\n ' \"constant\", \"constant_with_warmup\"]'\n ),\n )\n parser.add_argument(\n \"--lr_warmup_steps\", type=int, default=500, help=\"Number of steps for the warmup in the lr scheduler.\"\n )\n parser.add_argument(\n \"--lr_num_cycles\",\n type=int,\n default=1,\n help=\"Number of hard resets of the lr in cosine_with_restarts scheduler.\",\n )\n parser.add_argument(\"--lr_power\", type=float, default=1.0, help=\"Power factor of the polynomial scheduler.\")\n parser.add_argument(\n \"--use_8bit_adam\", action=\"store_true\", help=\"Whether or not to use 8-bit Adam from bitsandbytes.\"\n )\n parser.add_argument(\"--adam_beta1\", type=float, default=0.9, help=\"The beta1 parameter for the Adam optimizer.\")\n parser.add_argument(\"--adam_beta2\", type=float, default=0.999, help=\"The beta2 parameter for the Adam optimizer.\")\n parser.add_argument(\"--adam_weight_decay\", type=float, default=1e-2, help=\"Weight decay to use.\")\n parser.add_argument(\"--adam_epsilon\", type=float, default=1e-08, help=\"Epsilon value for the Adam optimizer\")\n parser.add_argument(\"--max_grad_norm\", default=1.0, type=float, help=\"Max gradient norm.\")\n parser.add_argument(\"--push_to_hub\", action=\"store_true\", help=\"Whether or not to push the model to the Hub.\")\n parser.add_argument(\"--hub_token\", type=str, default=None, help=\"The token to use to push to the Model Hub.\")\n parser.add_argument(\n \"--hub_model_id\",\n type=str,\n default=None,\n help=\"The name of the repository to keep in sync with the local `output_dir`.\",\n )\n parser.add_argument(\n \"--logging_dir\",\n type=str,\n default=\"logs\",\n help=(\n \"[TensorBoard](https://www.tensorflow.org/tensorboard) log directory. Will default to\"\n \" *output_dir/runs/**CURRENT_DATETIME_HOSTNAME***.\"\n ),\n )\n parser.add_argument(\n \"--allow_tf32\",\n action=\"store_true\",\n help=(\n \"Whether or not to allow TF32 on Ampere GPUs. Can be used to speed up training. For more information, see\"\n \" https://pytorch.org/docs/stable/notes/cuda.html#tensorfloat-32-tf32-on-ampere-devices\"\n ),\n )\n parser.add_argument(\n \"--report_to\",\n type=str,\n default=\"tensorboard\",\n help=(\n 'The integration to report the results and logs to. Supported platforms are `\"tensorboard\"`'\n ' (default), `\"wandb\"` and `\"comet_ml\"`. Use `\"all\"` to report to all integrations.'\n ),\n )\n parser.add_argument(\n \"--validation_steps\",\n type=int,\n default=None,\n help=(\n \"Run validation every X steps. Validation consists of running the prompt(s) `validation_prompt` \"\n \"multiple times (`validation_number_images`) and logging the images.\"\n ),\n )\n parser.add_argument(\n \"--validation_prompt\",\n type=str,\n default=None,\n help=\"A prompt that is used during validation to verify that the model is learning. You can use commas to \"\n \"define multiple negative prompts. This parameter can be defined also within the file given by \"\n \"`concepts_list` parameter in the respective subject.\",\n )\n parser.add_argument(\n \"--validation_number_images\",\n type=int,\n default=4,\n help=\"Number of images that should be generated during validation with the validation parameters given. This \"\n \"can be defined within the file given by `concepts_list` parameter in the respective subject.\",\n )\n parser.add_argument(\n \"--validation_negative_prompt\",\n type=str,\n default=None,\n help=\"A negative prompt that is used during validation to verify that the model is learning. You can use commas\"\n \" to define multiple negative prompts, each one corresponding to a validation prompt. This parameter can \"\n \"be defined also within the file given by `concepts_list` parameter in the respective subject.\",\n )\n parser.add_argument(\n \"--validation_inference_steps\",\n type=int,\n default=25,\n help=\"Number of inference steps (denoising steps) to run during validation. This can be defined within the \"\n \"file given by `concepts_list` parameter in the respective subject.\",\n )\n parser.add_argument(\n \"--validation_guidance_scale\",\n type=float,\n default=7.5,\n help=\"To control how much the image generation process follows the text prompt. This can be defined within the \"\n \"file given by `concepts_list` parameter in the respective subject.\",\n )\n parser.add_argument(\n \"--mixed_precision\",\n type=str,\n default=None,\n choices=[\"no\", \"fp16\", \"bf16\"],\n help=(\n \"Whether to use mixed precision. Choose between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >=\"\n \" 1.10.and an Nvidia Ampere GPU. Default to the value of accelerate config of the current system or the\"\n \" flag passed with the `accelerate.launch` command. Use this argument to override the accelerate config.\"\n ),\n )\n parser.add_argument(\n \"--prior_generation_precision\",\n type=str,\n default=None,\n choices=[\"no\", \"fp32\", \"fp16\", \"bf16\"],\n help=(\n \"Choose prior generation precision between fp32, fp16 and bf16 (bfloat16). Bf16 requires PyTorch >=\"\n \" 1.10.and an Nvidia Ampere GPU. Default to fp16 if a GPU is available else fp32.\"\n ),\n )\n parser.add_argument(\"--local_rank\", type=int, default=-1, help=\"For distributed training: local_rank\")\n parser.add_argument(\n \"--enable_xformers_memory_efficient_attention\", action=\"store_true\", help=\"Whether or not to use xformers.\"\n )\n parser.add_argument(\n \"--set_grads_to_none\",\n action=\"store_true\",\n help=(\n \"Save more memory by using setting grads to None instead of zero. Be aware, that this changes certain\"\n \" behaviors, so disable this argument if it causes any problems. More info:\"\n \" https://pytorch.org/docs/stable/generated/torch.optim.Optimizer.zero_grad.html\"\n ),\n )\n parser.add_argument(\n \"--concepts_list\",\n type=str,\n default=None,\n help=\"Path to json file containing a list of multiple concepts, will overwrite parameters like instance_prompt,\"\n \" class_prompt, etc.\",\n )\n\n if input_args:\n args = parser.parse_args(input_args)\n else:\n args = parser.parse_args()\n\n if not args.concepts_list and (not args.instance_data_dir or not args.instance_prompt):\n raise ValueError(\n \"You must specify either instance parameters (data directory, prompt, etc.) or use \"\n \"the `concept_list` parameter and specify them within the file.\"\n )\n\n if args.concepts_list:\n if args.instance_prompt:\n raise ValueError(\"If you are using `concepts_list` parameter, define the instance prompt within the file.\")\n if args.instance_data_dir:\n raise ValueError(\n \"If you are using `concepts_list` parameter, define the instance data directory within the file.\"\n )\n if args.validation_steps and (args.validation_prompt or args.validation_negative_prompt):\n raise ValueError(\n \"If you are using `concepts_list` parameter, define validation parameters for \"\n \"each subject within the file:\\n - `validation_prompt`.\"\n \"\\n - `validation_negative_prompt`.\\n - `validation_guidance_scale`.\"\n \"\\n - `validation_number_images`.\\n - `validation_prompt`.\"\n \"\\n - `validation_inference_steps`.\\nThe `validation_steps` parameter is the only one \"\n \"that needs to be defined outside the file.\"\n )\n\n env_local_rank = int(environ.get(\"LOCAL_RANK\", -1))\n if env_local_rank != -1 and env_local_rank != args.local_rank:\n args.local_rank = env_local_rank\n\n if args.with_prior_preservation:\n if not args.concepts_list:\n if not args.class_data_dir:\n raise ValueError(\"You must specify a data directory for class images.\")\n if not args.class_prompt:\n raise ValueError(\"You must specify prompt for class images.\")\n else:\n if args.class_data_dir:\n raise ValueError(\n \"If you are using `concepts_list` parameter, define the class data directory within the file.\"\n )\n if args.class_prompt:\n raise ValueError(\n \"If you are using `concepts_list` parameter, define the class prompt within the file.\"\n )\n else:\n # logger is not available yet\n if not args.class_data_dir:\n warnings.warn(\n \"Ignoring `class_data_dir` parameter, you need to use it together with `with_prior_preservation`.\"\n )\n if not args.class_prompt:\n warnings.warn(\n \"Ignoring `class_prompt` parameter, you need to use it together with `with_prior_preservation`.\"\n )\n\n return args\n\n\nclass DreamBoothDataset(Dataset):\n \"\"\"\n A dataset to prepare the instance and class images with the prompts for fine-tuning the model.\n It pre-processes the images and then tokenizes prompts.\n \"\"\"\n\n def __init__(\n self,\n instance_data_root,\n instance_prompt,\n tokenizer,\n class_data_root=None,\n class_prompt=None,\n size=512,\n center_crop=False,\n ):\n self.size = size\n self.center_crop = center_crop\n self.tokenizer = tokenizer\n\n self.instance_data_root = []\n self.instance_images_path = []\n self.num_instance_images = []\n self.instance_prompt = []\n self.class_data_root = [] if class_data_root is not None else None\n self.class_images_path = []\n self.num_class_images = []\n self.class_prompt = []\n self._length = 0\n\n for i in range(len(instance_data_root)):\n self.instance_data_root.append(Path(instance_data_root[i]))\n if not self.instance_data_root[i].exists():\n raise ValueError(\"Instance images root doesn't exists.\")\n\n self.instance_images_path.append(list(Path(instance_data_root[i]).iterdir()))\n self.num_instance_images.append(len(self.instance_images_path[i]))\n self.instance_prompt.append(instance_prompt[i])\n self._length += self.num_instance_images[i]\n\n if class_data_root is not None:\n self.class_data_root.append(Path(class_data_root[i]))\n self.class_data_root[i].mkdir(parents=True, exist_ok=True)\n self.class_images_path.append(list(self.class_data_root[i].iterdir()))\n self.num_class_images.append(len(self.class_images_path))\n if self.num_class_images[i] > self.num_instance_images[i]:\n self._length -= self.num_instance_images[i]\n self._length += self.num_class_images[i]\n self.class_prompt.append(class_prompt[i])\n\n self.image_transforms = transforms.Compose(\n [\n transforms.Resize(size, interpolation=transforms.InterpolationMode.BILINEAR),\n transforms.CenterCrop(size) if center_crop else transforms.RandomCrop(size),\n transforms.ToTensor(),\n transforms.Normalize([0.5], [0.5]),\n ]\n )\n\n def __len__(self):\n return self._length\n\n def __getitem__(self, index):\n example = {}\n for i in range(len(self.instance_images_path)):\n instance_image = Image.open(self.instance_images_path[i][index % self.num_instance_images[i]])\n if not instance_image.mode == \"RGB\":\n instance_image = instance_image.convert(\"RGB\")\n example[f\"instance_images_{i}\"] = self.image_transforms(instance_image)\n example[f\"instance_prompt_ids_{i}\"] = self.tokenizer(\n self.instance_prompt[i],\n truncation=True,\n padding=\"max_length\",\n max_length=self.tokenizer.model_max_length,\n return_tensors=\"pt\",\n ).input_ids\n\n if self.class_data_root:\n for i in range(len(self.class_data_root)):\n class_image = Image.open(self.class_images_path[i][index % self.num_class_images[i]])\n if not class_image.mode == \"RGB\":\n class_image = class_image.convert(\"RGB\")\n example[f\"class_images_{i}\"] = self.image_transforms(class_image)\n example[f\"class_prompt_ids_{i}\"] = self.tokenizer(\n self.class_prompt[i],\n truncation=True,\n padding=\"max_length\",\n max_length=self.tokenizer.model_max_length,\n return_tensors=\"pt\",\n ).input_ids\n\n return example\n\n\ndef collate_fn(num_instances, examples, with_prior_preservation=False):\n input_ids = []\n pixel_values = []\n\n for i in range(num_instances):\n input_ids += [example[f\"instance_prompt_ids_{i}\"] for example in examples]\n pixel_values += [example[f\"instance_images_{i}\"] for example in examples]\n\n # Concat class and instance examples for prior preservation.\n # We do this to avoid doing two forward passes.\n if with_prior_preservation:\n for i in range(num_instances):\n input_ids += [example[f\"class_prompt_ids_{i}\"] for example in examples]\n pixel_values += [example[f\"class_images_{i}\"] for example in examples]\n\n pixel_values = torch.stack(pixel_values)\n pixel_values = pixel_values.to(memory_format=torch.contiguous_format).float()\n\n input_ids = torch.cat(input_ids, dim=0)\n\n batch = {\n \"input_ids\": input_ids,\n \"pixel_values\": pixel_values,\n }\n return batch\n\n\nclass PromptDataset(Dataset):\n \"\"\"A simple dataset to prepare the prompts to generate class images on multiple GPUs.\"\"\"\n\n def __init__(self, prompt, num_samples):\n self.prompt = prompt\n self.num_samples = num_samples\n\n def __len__(self):\n return self.num_samples\n\n def __getitem__(self, index):\n example = {}\n example[\"prompt\"] = self.prompt\n example[\"index\"] = index\n return example\n\n\ndef main(args):\n logging_dir = Path(args.output_dir, args.logging_dir)\n accelerator_project_config = ProjectConfiguration(\n total_limit=args.checkpoints_total_limit, project_dir=args.output_dir, logging_dir=logging_dir\n )\n accelerator = Accelerator(\n gradient_accumulation_steps=args.gradient_accumulation_steps,\n mixed_precision=args.mixed_precision,\n log_with=args.report_to,\n project_config=accelerator_project_config,\n )\n\n if args.report_to == \"wandb\":\n if not is_wandb_available():\n raise ImportError(\"Make sure to install wandb if you want to use it for logging during training.\")\n\n # Currently, it's not possible to do gradient accumulation when training two models with accelerate.accumulate\n # This will be enabled soon in accelerate. For now, we don't allow gradient accumulation when training two models.\n # TODO (patil-suraj): Remove this check when gradient accumulation with two models is enabled in accelerate.\n if args.train_text_encoder and args.gradient_accumulation_steps > 1 and accelerator.num_processes > 1:\n raise ValueError(\n \"Gradient accumulation is not supported when training the text encoder in distributed training. \"\n \"Please set gradient_accumulation_steps to 1. This feature will be supported in the future.\"\n )\n\n instance_data_dir = []\n instance_prompt = []\n class_data_dir = [] if args.with_prior_preservation else None\n class_prompt = [] if args.with_prior_preservation else None\n if args.concepts_list:\n with open(args.concepts_list, \"r\") as f:\n concepts_list = json.load(f)\n\n if args.validation_steps:\n args.validation_prompt = []\n args.validation_number_images = []\n args.validation_negative_prompt = []\n args.validation_inference_steps = []\n args.validation_guidance_scale = []\n\n for concept in concepts_list:\n instance_data_dir.append(concept[\"instance_data_dir\"])\n instance_prompt.append(concept[\"instance_prompt\"])\n\n if args.with_prior_preservation:\n try:\n class_data_dir.append(concept[\"class_data_dir\"])\n class_prompt.append(concept[\"class_prompt\"])\n except KeyError:\n raise KeyError(\n \"`class_data_dir` or `class_prompt` not found in concepts_list while using \"\n \"`with_prior_preservation`.\"\n )\n else:\n if \"class_data_dir\" in concept:\n warnings.warn(\n \"Ignoring `class_data_dir` key, to use it you need to enable `with_prior_preservation`.\"\n )\n if \"class_prompt\" in concept:\n warnings.warn(\n \"Ignoring `class_prompt` key, to use it you need to enable `with_prior_preservation`.\"\n )\n\n if args.validation_steps:\n args.validation_prompt.append(concept.get(\"validation_prompt\", None))\n args.validation_number_images.append(concept.get(\"validation_number_images\", 4))\n args.validation_negative_prompt.append(concept.get(\"validation_negative_prompt\", None))\n args.validation_inference_steps.append(concept.get(\"validation_inference_steps\", 25))\n args.validation_guidance_scale.append(concept.get(\"validation_guidance_scale\", 7.5))\n else:\n # Parse instance and class inputs, and double check that lengths match\n instance_data_dir = args.instance_data_dir.split(\",\")\n instance_prompt = args.instance_prompt.split(\",\")\n assert all(\n x == len(instance_data_dir) for x in [len(instance_data_dir), len(instance_prompt)]\n ), \"Instance data dir and prompt inputs are not of the same length.\"\n\n if args.with_prior_preservation:\n class_data_dir = args.class_data_dir.split(\",\")\n class_prompt = args.class_prompt.split(\",\")\n assert all(\n x == len(instance_data_dir)\n for x in [len(instance_data_dir), len(instance_prompt), len(class_data_dir), len(class_prompt)]\n ), \"Instance & class data dir or prompt inputs are not of the same length.\"\n\n if args.validation_steps:\n validation_prompts = args.validation_prompt.split(\",\")\n num_of_validation_prompts = len(validation_prompts)\n args.validation_prompt = validation_prompts\n args.validation_number_images = [args.validation_number_images] * num_of_validation_prompts\n\n negative_validation_prompts = [None] * num_of_validation_prompts\n if args.validation_negative_prompt:\n negative_validation_prompts = args.validation_negative_prompt.split(\",\")\n while len(negative_validation_prompts) < num_of_validation_prompts:\n negative_validation_prompts.append(None)\n args.validation_negative_prompt = negative_validation_prompts\n\n assert num_of_validation_prompts == len(\n negative_validation_prompts\n ), \"The length of negative prompts for validation is greater than the number of validation prompts.\"\n args.validation_inference_steps = [args.validation_inference_steps] * num_of_validation_prompts\n args.validation_guidance_scale = [args.validation_guidance_scale] * num_of_validation_prompts\n\n # Make one log on every process with the configuration for debugging.\n logging.basicConfig(\n format=\"%(asctime)s - %(levelname)s - %(name)s - %(message)s\",\n datefmt=\"%m/%d/%Y %H:%M:%S\",\n level=logging.INFO,\n )\n logger.info(accelerator.state, main_process_only=False)\n if accelerator.is_local_main_process:\n datasets.utils.logging.set_verbosity_warning()\n transformers.utils.logging.set_verbosity_warning()\n diffusers.utils.logging.set_verbosity_info()\n else:\n datasets.utils.logging.set_verbosity_error()\n transformers.utils.logging.set_verbosity_error()\n diffusers.utils.logging.set_verbosity_error()\n\n # If passed along, set the training seed now.\n if args.seed is not None:\n set_seed(args.seed)\n\n # Generate class images if prior preservation is enabled.\n if args.with_prior_preservation:\n for i in range(len(class_data_dir)):\n class_images_dir = Path(class_data_dir[i])\n if not class_images_dir.exists():\n class_images_dir.mkdir(parents=True)\n cur_class_images = len(list(class_images_dir.iterdir()))\n\n if cur_class_images < args.num_class_images:\n torch_dtype = torch.float16 if accelerator.device.type == \"cuda\" else torch.float32\n if args.prior_generation_precision == \"fp32\":\n torch_dtype = torch.float32\n elif args.prior_generation_precision == \"fp16\":\n torch_dtype = torch.float16\n elif args.prior_generation_precision == \"bf16\":\n torch_dtype = torch.bfloat16\n pipeline = DiffusionPipeline.from_pretrained(\n args.pretrained_model_name_or_path,\n torch_dtype=torch_dtype,\n safety_checker=None,\n revision=args.revision,\n )\n pipeline.set_progress_bar_config(disable=True)\n\n num_new_images = args.num_class_images - cur_class_images\n logger.info(f\"Number of class images to sample: {num_new_images}.\")\n\n sample_dataset = PromptDataset(class_prompt[i], num_new_images)\n sample_dataloader = torch.utils.data.DataLoader(sample_dataset, batch_size=args.sample_batch_size)\n\n sample_dataloader = accelerator.prepare(sample_dataloader)\n pipeline.to(accelerator.device)\n\n for example in tqdm(\n sample_dataloader, desc=\"Generating class images\", disable=not accelerator.is_local_main_process\n ):\n images = pipeline(example[\"prompt\"]).images\n\n for ii, image in enumerate(images):\n hash_image = hashlib.sha1(image.tobytes()).hexdigest()\n image_filename = (\n class_images_dir / f\"{example['index'][ii] + cur_class_images}-{hash_image}.jpg\"\n )\n image.save(image_filename)\n\n # Clean up the memory deleting one-time-use variables.\n del pipeline\n del sample_dataloader\n del sample_dataset\n if torch.cuda.is_available():\n torch.cuda.empty_cache()\n\n # Handle the repository creation\n if accelerator.is_main_process:\n if args.output_dir is not None:\n makedirs(args.output_dir, exist_ok=True)\n\n if args.push_to_hub:\n repo_id = create_repo(\n repo_id=args.hub_model_id or Path(args.output_dir).name, exist_ok=True, token=args.hub_token\n ).repo_id\n\n # Load the tokenizer\n tokenizer = None\n if args.tokenizer_name:\n tokenizer = AutoTokenizer.from_pretrained(args.tokenizer_name, revision=args.revision, use_fast=False)\n elif args.pretrained_model_name_or_path:\n tokenizer = AutoTokenizer.from_pretrained(\n args.pretrained_model_name_or_path,\n subfolder=\"tokenizer\",\n revision=args.revision,\n use_fast=False,\n )\n\n # import correct text encoder class\n text_encoder_cls = import_model_class_from_model_name_or_path(args.pretrained_model_name_or_path, args.revision)\n\n # Load scheduler and models\n noise_scheduler = DDPMScheduler.from_pretrained(args.pretrained_model_name_or_path, subfolder=\"scheduler\")\n text_encoder = text_encoder_cls.from_pretrained(\n args.pretrained_model_name_or_path, subfolder=\"text_encoder\", revision=args.revision\n )\n vae = AutoencoderKL.from_pretrained(args.pretrained_model_name_or_path, subfolder=\"vae\", revision=args.revision)\n unet = UNet2DConditionModel.from_pretrained(\n args.pretrained_model_name_or_path, subfolder=\"unet\", revision=args.revision\n )\n\n vae.requires_grad_(False)\n if not args.train_text_encoder:\n text_encoder.requires_grad_(False)\n\n if args.enable_xformers_memory_efficient_attention:\n if is_xformers_available():\n unet.enable_xformers_memory_efficient_attention()\n else:\n raise ValueError(\"xformers is not available. Make sure it is installed correctly\")\n\n if args.gradient_checkpointing:\n unet.enable_gradient_checkpointing()\n if args.train_text_encoder:\n text_encoder.gradient_checkpointing_enable()\n\n # Enable TF32 for faster training on Ampere GPUs,\n # cf https://pytorch.org/docs/stable/notes/cuda.html#tensorfloat-32-tf32-on-ampere-devices\n if args.allow_tf32:\n torch.backends.cuda.matmul.allow_tf32 = True\n\n if args.scale_lr:\n args.learning_rate = (\n args.learning_rate * args.gradient_accumulation_steps * args.train_batch_size * accelerator.num_processes\n )\n\n # Use 8-bit Adam for lower memory usage or to fine-tune the model in 16GB GPUs\n if args.use_8bit_adam:\n try:\n import bitsandbytes as bnb\n except ImportError:\n raise ImportError(\n \"To use 8-bit Adam, please install the bitsandbytes library: `pip install bitsandbytes`.\"\n )\n\n optimizer_class = bnb.optim.AdamW8bit\n else:\n optimizer_class = torch.optim.AdamW\n\n # Optimizer creation\n params_to_optimize = (\n itertools.chain(unet.parameters(), text_encoder.parameters()) if args.train_text_encoder else unet.parameters()\n )\n optimizer = optimizer_class(\n params_to_optimize,\n lr=args.learning_rate,\n betas=(args.adam_beta1, args.adam_beta2),\n weight_decay=args.adam_weight_decay,\n eps=args.adam_epsilon,\n )\n\n # Dataset and DataLoaders creation:\n train_dataset = DreamBoothDataset(\n instance_data_root=instance_data_dir,\n instance_prompt=instance_prompt,\n class_data_root=class_data_dir,\n class_prompt=class_prompt,\n tokenizer=tokenizer,\n size=args.resolution,\n center_crop=args.center_crop,\n )\n\n train_dataloader = torch.utils.data.DataLoader(\n train_dataset,\n batch_size=args.train_batch_size,\n shuffle=True,\n collate_fn=lambda examples: collate_fn(len(instance_data_dir), examples, args.with_prior_preservation),\n num_workers=1,\n )\n\n # Scheduler and math around the number of training steps.\n overrode_max_train_steps = False\n num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps)\n if args.max_train_steps is None:\n args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch\n overrode_max_train_steps = True\n\n lr_scheduler = get_scheduler(\n args.lr_scheduler,\n optimizer=optimizer,\n num_warmup_steps=args.lr_warmup_steps * accelerator.num_processes,\n num_training_steps=args.max_train_steps * accelerator.num_processes,\n num_cycles=args.lr_num_cycles,\n power=args.lr_power,\n )\n\n # Prepare everything with our `accelerator`.\n if args.train_text_encoder:\n unet, text_encoder, optimizer, train_dataloader, lr_scheduler = accelerator.prepare(\n unet, text_encoder, optimizer, train_dataloader, lr_scheduler\n )\n else:\n unet, optimizer, train_dataloader, lr_scheduler = accelerator.prepare(\n unet, optimizer, train_dataloader, lr_scheduler\n )\n\n # For mixed precision training we cast the text_encoder and vae weights to half-precision\n # as these models are only used for inference, keeping weights in full precision is not required.\n weight_dtype = torch.float32\n if accelerator.mixed_precision == \"fp16\":\n weight_dtype = torch.float16\n elif accelerator.mixed_precision == \"bf16\":\n weight_dtype = torch.bfloat16\n\n # Move vae and text_encoder to device and cast to weight_dtype\n vae.to(accelerator.device, dtype=weight_dtype)\n if not args.train_text_encoder:\n text_encoder.to(accelerator.device, dtype=weight_dtype)\n\n # We need to recalculate our total training steps as the size of the training dataloader may have changed.\n num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps)\n if overrode_max_train_steps:\n args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch\n # Afterwards we recalculate our number of training epochs\n args.num_train_epochs = math.ceil(args.max_train_steps / num_update_steps_per_epoch)\n\n # We need to initialize the trackers we use, and also store our configuration.\n # The trackers initialize automatically on the main process.\n if accelerator.is_main_process:\n accelerator.init_trackers(\"dreambooth\", config=vars(args))\n\n # Train!\n total_batch_size = args.train_batch_size * accelerator.num_processes * args.gradient_accumulation_steps\n\n logger.info(\"***** Running training *****\")\n logger.info(f\" Num examples = {len(train_dataset)}\")\n logger.info(f\" Num batches each epoch = {len(train_dataloader)}\")\n logger.info(f\" Num Epochs = {args.num_train_epochs}\")\n logger.info(f\" Instantaneous batch size per device = {args.train_batch_size}\")\n logger.info(f\" Total train batch size (w. parallel, distributed & accumulation) = {total_batch_size}\")\n logger.info(f\" Gradient Accumulation steps = {args.gradient_accumulation_steps}\")\n logger.info(f\" Total optimization steps = {args.max_train_steps}\")\n global_step = 0\n first_epoch = 0\n\n # Potentially load in the weights and states from a previous save\n if args.resume_from_checkpoint:\n if args.resume_from_checkpoint != \"latest\":\n path = basename(args.resume_from_checkpoint)\n else:\n # Get the mos recent checkpoint\n dirs = listdir(args.output_dir)\n dirs = [d for d in dirs if d.startswith(\"checkpoint\")]\n dirs = sorted(dirs, key=lambda x: int(x.split(\"-\")[1]))\n path = dirs[-1] if len(dirs) > 0 else None\n\n if path is None:\n accelerator.print(\n f\"Checkpoint '{args.resume_from_checkpoint}' does not exist. Starting a new training run.\"\n )\n args.resume_from_checkpoint = None\n else:\n accelerator.print(f\"Resuming from checkpoint {path}\")\n accelerator.load_state(join(args.output_dir, path))\n global_step = int(path.split(\"-\")[1])\n\n resume_global_step = global_step * args.gradient_accumulation_steps\n first_epoch = global_step // num_update_steps_per_epoch\n resume_step = resume_global_step % (num_update_steps_per_epoch * args.gradient_accumulation_steps)\n\n # Only show the progress bar once on each machine.\n progress_bar = tqdm(range(global_step, args.max_train_steps), disable=not accelerator.is_local_main_process)\n progress_bar.set_description(\"Steps\")\n\n for epoch in range(first_epoch, args.num_train_epochs):\n unet.train()\n if args.train_text_encoder:\n text_encoder.train()\n for step, batch in enumerate(train_dataloader):\n # Skip steps until we reach the resumed step\n if args.resume_from_checkpoint and epoch == first_epoch and step < resume_step:\n if step % args.gradient_accumulation_steps == 0:\n progress_bar.update(1)\n continue\n\n with accelerator.accumulate(unet):\n # Convert images to latent space\n latents = vae.encode(batch[\"pixel_values\"].to(dtype=weight_dtype)).latent_dist.sample()\n latents = latents * vae.config.scaling_factor\n\n # Sample noise that we'll add to the latents\n noise = torch.randn_like(latents)\n bsz = latents.shape[0]\n # Sample a random timestep for each image\n time_steps = torch.randint(\n 0, noise_scheduler.config.num_train_timesteps, (bsz,), device=latents.device\n )\n time_steps = time_steps.long()\n\n # Add noise to the latents according to the noise magnitude at each timestep\n # (this is the forward diffusion process)\n noisy_latents = noise_scheduler.add_noise(latents, noise, time_steps)\n\n # Get the text embedding for conditioning\n encoder_hidden_states = text_encoder(batch[\"input_ids\"])[0]\n\n # Predict the noise residual\n model_pred = unet(noisy_latents, time_steps, encoder_hidden_states).sample\n\n # Get the target for loss depending on the prediction type\n if noise_scheduler.config.prediction_type == \"epsilon\":\n target = noise\n elif noise_scheduler.config.prediction_type == \"v_prediction\":\n target = noise_scheduler.get_velocity(latents, noise, time_steps)\n else:\n raise ValueError(f\"Unknown prediction type {noise_scheduler.config.prediction_type}\")\n\n if args.with_prior_preservation:\n # Chunk the noise and model_pred into two parts and compute the loss on each part separately.\n model_pred, model_pred_prior = torch.chunk(model_pred, 2, dim=0)\n target, target_prior = torch.chunk(target, 2, dim=0)\n\n # Compute instance loss\n loss = F.mse_loss(model_pred.float(), target.float(), reduction=\"mean\")\n\n # Compute prior loss\n prior_loss = F.mse_loss(model_pred_prior.float(), target_prior.float(), reduction=\"mean\")\n\n # Add the prior loss to the instance loss.\n loss = loss + args.prior_loss_weight * prior_loss\n else:\n loss = F.mse_loss(model_pred.float(), target.float(), reduction=\"mean\")\n\n accelerator.backward(loss)\n if accelerator.sync_gradients:\n params_to_clip = (\n itertools.chain(unet.parameters(), text_encoder.parameters())\n if args.train_text_encoder\n else unet.parameters()\n )\n accelerator.clip_grad_norm_(params_to_clip, args.max_grad_norm)\n optimizer.step()\n lr_scheduler.step()\n optimizer.zero_grad(set_to_none=args.set_grads_to_none)\n\n # Checks if the accelerator has performed an optimization step behind the scenes\n if accelerator.sync_gradients:\n progress_bar.update(1)\n global_step += 1\n\n if accelerator.is_main_process:\n if global_step % args.checkpointing_steps == 0:\n save_path = join(args.output_dir, f\"checkpoint-{global_step}\")\n accelerator.save_state(save_path)\n logger.info(f\"Saved state to {save_path}\")\n\n if (\n args.validation_steps\n and any(args.validation_prompt)\n and global_step % args.validation_steps == 0\n ):\n images_set = generate_validation_images(\n text_encoder, tokenizer, unet, vae, args, accelerator, weight_dtype\n )\n for images, validation_prompt in zip(images_set, args.validation_prompt):\n if len(images) > 0:\n label = str(uuid.uuid1())[:8] # generate an id for different set of images\n log_validation_images_to_tracker(\n images, label, validation_prompt, accelerator, global_step\n )\n\n logs = {\"loss\": loss.detach().item(), \"lr\": lr_scheduler.get_last_lr()[0]}\n progress_bar.set_postfix(**logs)\n accelerator.log(logs, step=global_step)\n\n if global_step >= args.max_train_steps:\n break\n\n # Create the pipeline using the trained modules and save it.\n accelerator.wait_for_everyone()\n if accelerator.is_main_process:\n pipeline = DiffusionPipeline.from_pretrained(\n args.pretrained_model_name_or_path,\n unet=accelerator.unwrap_model(unet),\n text_encoder=accelerator.unwrap_model(text_encoder),\n revision=args.revision,\n )\n pipeline.save_pretrained(args.output_dir)\n\n if args.push_to_hub:\n upload_folder(\n repo_id=repo_id,\n folder_path=args.output_dir,\n commit_message=\"End of training\",\n ignore_patterns=[\"step_*\", \"epoch_*\"],\n )\n\n accelerator.end_training()\n\n\nif __name__ == \"__main__\":\n args = parse_args()\n main(args)\n","repo_name":"huggingface/diffusers","sub_path":"examples/research_projects/multi_subject_dreambooth/train_multi_subject_dreambooth.py","file_name":"train_multi_subject_dreambooth.py","file_ext":"py","file_size_in_byte":49694,"program_lang":"python","lang":"en","doc_type":"code","stars":19077,"dataset":"github-code","pt":"85"} +{"seq_id":"13589481410","text":"import mmh3\nimport struct\n\nlocal_file_name='doc'\nkey_size=96\nhash_size=2147483640\ndim=64\nwith open(local_file_name, 'rb') as bin_file:\n while True:\n key = bin_file.read(key_size)\n if len(key) < key_size:\n break\n key = key.strip(b'\\x00').decode('utf-8')\n #decode('utf-8')\n vector = bin_file.read(dim*4)\n vector = struct.unpack(\"{}f\".format(dim), vector) # vector type is tuple\n ## mmh3.hash(key) return a signed 32 int, may < 0. need & 0xffffffff\n hash_value = (mmh3.hash(key) & 0xffffffff) % hash_size\n print (key + \"\\t\" + str(hash_value))\n","repo_name":"Serene-Guo/python_utils","sub_path":"murmurhash_test.py","file_name":"murmurhash_test.py","file_ext":"py","file_size_in_byte":617,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"4379497064","text":"from django import forms\nfrom django.contrib.auth.models import User\nfrom django.shortcuts import get_object_or_404, render,redirect,get_list_or_404,HttpResponseRedirect\nfrom django.contrib.auth import authenticate, login\nfrom .forms import LoginForm, RegisterForm\n\ndef register_user(request):\n form = RegisterForm()\n if request.method=='POST':\n # print(request.POST)\n form= RegisterForm(request.POST)\n if form.is_valid():\n form.save_user()\n return redirect(\"index\")\n return render(\n request=request,\n template_name='user/register.html',\n context={\n 'form':form\n }\n )\n\ndef login_user(request):\n form = LoginForm()\n message = \"\"\n if request.method =='POST':\n form = LoginForm(request.POST)\n if form.is_valid():\n # Hàm authenticate nhận username và password\n # Nếu thông tin đúng thì return User Object\n # Không đúng thì return None\n user = authenticate(\n username=form.cleaned_data['username'],\n password= form.cleaned_data['password'],\n )\n if user: # Kiem tra not None la True\n # print('Thông tin đúng')\n # Thông tin đúng giữ trạng thái đăng nhập user\n login(request,user)\n # Thay vì kiểm tra redirect về index, phải kiểm tra cái tham số getnext trên web\n if request.GET.get('next'):\n return HttpResponseRedirect(request.GET.get('next'))\n return redirect ('index')\n else:\n # print('Thông tin sai')\n message = \" Thông tin nhập không đúng.Vui lòng nhập lại\"\n\n return render(\n request=request,\n template_name='user/login.html',\n context={\n 'form':form,\n 'message' : message\n }\n )\n\n\n\n","repo_name":"ThaoHn18/mini2","sub_path":"myapp/user_views.py","file_name":"user_views.py","file_ext":"py","file_size_in_byte":1953,"program_lang":"python","lang":"vi","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"2058223531","text":"# -*- encoding: utf-8 -*-\n\"\"\"\n Created by Ênio Viana at 10/10/2021 at 16:20:46\n Project: processos-estocasticos [out, 2021]\n\"\"\"\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\nclass Plot:\n\n @staticmethod\n def plot_histogram(vector: np.ndarray, sigma: [int, float], mu: [int, float], title: str):\n count, bins, ignored = plt.hist(vector, 30, density=True)\n plt.plot(bins, 1 / (sigma * np.sqrt(2 * np.pi)) *\n np.exp(- (bins - mu) ** 2 / (2 * sigma ** 2)),\n linewidth=2, color='r')\n plt.title(title)\n plt.show()\n\n @staticmethod\n def plot_scatter(vector_x: np.ndarray, vector_y: np.ndarray, title: str):\n plt.scatter(vector_x, vector_y, s=50, alpha=0.5)\n plt.title(title)\n plt.show()\n","repo_name":"eniocc/processos-estocasticos","sub_path":"atividade_01/Plot.py","file_name":"Plot.py","file_ext":"py","file_size_in_byte":779,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"38791599228","text":"\"\"\"\nAR_OpenRenderFolder\n\nAuthor: Arttu Rautio (aturtur)\nWebsite: http://aturtur.com/\nName-US: AR_OpenRenderFolder\nVersion: 1.0\nDescription-US: Opens folder where project is rendered\nNOTE: Does not support all of the tokens!\n\nWritten for Maxon Cinema 4D R21.207\nPython version 2.7.14\n\"\"\"\n# Libraries\nimport c4d\nimport os\nimport subprocess\nimport re\n\n\n# Functions\ndef CheckFolders(path):\n folders = path.split(\"..\\\\\")\n if len(folders)>1:\n p = doc.GetDocumentPath()\n for x in range(0, len(folders)-1):\n p = os.path.dirname(p)\n path = p + \"\\\\\" + folders[-1]\n current = path.split(\".\\\\\")\n if len(current)>1:\n path = doc.GetDocumentPath() + \"\\\\\" + current[1]\n return path\n\ndef main():\n doc = c4d.documents.GetActiveDocument() # Get active document\n bd = doc.GetActiveBaseDraw() # Get active base draw\n renderData = doc.GetActiveRenderData() # Get document active render data\n \n renderPath = renderData[c4d.RDATA_PATH]\n width = renderData[c4d.RDATA_XRES_VIRTUAL]\n height = renderData[c4d.RDATA_YRES_VIRTUAL]\n fps = renderData[c4d.RDATA_FRAMERATE]\n\n take = doc.GetTakeData().GetCurrentTake().GetName()\n camera = bd.GetSceneCamera(doc).GetName()\n \n tokenPrj = os.path.splitext(doc.GetDocumentName())[0]\n tokenPrj = str(tokenPrj.replace(\" \", \"_\"))\n tokenRes = str(int(width))+\"x\"+str(int(height))\n tokenFps = str(int(fps))\n tokenTake = str(take.replace(\" \", \"_\"))\n tokenCamera = str(camera.replace(\" \", \"_\"))\n\n renderPath = renderPath.replace(\"/\",\"\\\\\")\n\n path = renderPath.replace(\"$prj\", tokenPrj) # Solve project name ($prj) token\n path = path.replace(\"$res\", tokenRes) # Solve esolution ($res) token\n path = path.replace(\"$fps\", tokenFps) # Solve frame rate ($fps) token\n path = path.replace(\"$take\", tokenTake) # Solve take ($take) token\n path = path.replace(\"$camera\", tokenCamera) # Solve camera ($camera) token\n\n path = CheckFolders(path) \n path = os.path.dirname(path)\n \n subprocess.Popen(r'explorer \"'+path+'\"') # Open project folder\n\n# Execute main()\nif __name__=='__main__':\n main()","repo_name":"aturtur/cinema4d-scripts","sub_path":"AR_Scripts_1.0.16_R21_Deprecated/AR_OpenRenderFolder.py","file_name":"AR_OpenRenderFolder.py","file_ext":"py","file_size_in_byte":2162,"program_lang":"python","lang":"en","doc_type":"code","stars":328,"dataset":"github-code","pt":"85"} +{"seq_id":"22186336734","text":"from graphene_django.utils.testing import GraphQLTestCase\n\nfrom app_utils.testdata_factories import UserMainFactory\n\n\nclass TestAll(GraphQLTestCase):\n\n @classmethod\n def setUpTestData(cls):\n cls.user = UserMainFactory()\n\n def test_user_tokens(self):\n self.client.force_login(self.user, \"graphql_jwt.backends.JSONWebTokenBackend\")\n\n response = self.query(\n '''\n query q {\n esiUserTokens {\n id\n character {\n id\n }\n }\n }\n '''\n )\n\n self.assertEqual(self.user.token_set.count(), 1)\n\n token = self.user.token_set.first()\n\n self.assertJSONEqual(\n response.content,\n {\n 'data': {\n 'esiUserTokens': [\n {\n 'id': str(token.pk),\n 'character': {\n 'id': str(self.user.profile.main_character.pk)\n }\n }\n ]\n }\n }\n )\n","repo_name":"Maestro-Zacht/allianceauth-graphql","sub_path":"allianceauth_graphql/tests/test_esi.py","file_name":"test_esi.py","file_ext":"py","file_size_in_byte":1177,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"85"} +{"seq_id":"39195992311","text":"import pandas as pd\nimport numpy as np\n\nimport torch\nfrom sklearn.metrics import log_loss, roc_auc_score\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import LabelEncoder, MinMaxScaler\nfrom deepctr_torch.inputs import SparseFeat, DenseFeat, get_feature_names\n\nclass DeepFMDataLoader:\n def __init__(self, *, sparse_features, dense_features):\n self._sparse_feats = sparse_features\n self._dense_feats = dense_features\n \n def load(self, dataset):\n nn_input = pd.DataFrame()\n nn_input[self._sparse_feats] = dataset[self._sparse_feats]\n nn_input[self._dense_feats] = dataset[self._dense_feats]\n \n for feat in self._sparse_feats:\n encoder = LabelEncoder()\n nn_input[feat] = encoder.fit_transform(nn_input[feat])\n \n mms = MinMaxScaler(feature_range=(0,1))\n nn_input[self._dense_feats] = mms.fit_transform(nn_input[self._dense_feats])\n \n # problems may be here\n sparse_feature_columns = [\n SparseFeat(feat, vocabulary_size=nn_input[feat].nunique(), embedding_dim=4) \n for i, feat in enumerate(self._sparse_feats)\n ]\n\n dense_feature_columns = [DenseFeat(feat, 1,) for feat in self._dense_feats]\n \n dnn_feat_cols = sparse_feature_columns + dense_feature_columns\n linear_feat_cols = sparse_feature_columns + dense_feature_columns\n \n feat_names = get_feature_names(linear_feat_cols + dnn_feat_cols)\n return nn_input, dnn_feat_cols, linear_feat_cols, feat_names\n \n \ndef merge_feats(feats_a, feats_b):\n assert len(feats_a) == len(feats_b)\n merged = []\n for feat_a, feat_b in zip(feats_a, feats_b):\n if isinstance(feat_a, DenseFeat):\n continue\n if feat_a.vocabulary_size >= feat_b.vocabulary_size:\n merged.append(feat_a)\n else:\n merged.append(feat_b)\n return merged\n \n\nclass NNModelWrapper:\n def __init__(self, trained_nn):\n self._nn = trained_nn\n\n def predict_rating_matrix(self, nn_input, merged_df):\n y = self._nn.predict(nn_input)\n result = pd.DataFrame()\n result[\"rating\"] = y.reshape((len(y),))\n result[\"user_id\"] = merged_df[\"user_id\"]\n result[\"item_id\"] = merged_df[\"item_id\"]\n output_matrix = result.pivot(index=\"user_id\", columns=\"item_id\", values=\"rating\")\n return output_matrix","repo_name":"vldpro/SynEvaRec","sub_path":"modules/modules/deepfm.py","file_name":"deepfm.py","file_ext":"py","file_size_in_byte":2466,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"85"} +{"seq_id":"3410090927","text":"\r\ndef crime_standardization(crime_group, city_name, crime_assoc_list):\r\n city_crime_group = {\r\n new_key: new_val\r\n for keys, new_val in crime_assoc_list\r\n for new_key in keys\r\n }\r\n crime_group[city_name] = city_crime_group\r\n\r\n\r\nassoc_list1 = [ ([\"01A\"], \"murder\"), ([\"02\"], \"sexual assault\"), ([\"04A\", \"04B\"], \"aggravated assault\"),\r\n ([\"03\"], \"robbery\"), ([\"05\"], \"burglary\"), ([\"06\"], \"theft\"), ([\"07\"], \"motor vehicle theft\") ]\r\n\r\nassoc_list2 = [ ([\"11A\", \"11B\", \"11C\"], \"sexual assault\"), ([\"09A\"], \"murder\"), ([\"13A\"], \"aggravated assault\"), ([\"220\"], \"burglary\"),\r\n ([\"120\"], \"robbery\"), ([\"23A\", \"23B\", \"23C\", \"23D\", \"23E\", \"23F\", \"23G\", \"23H\"], \"theft\"), ([\"240\"], \"motor vehicle theft\") ]\r\n\r\nassoc_list3 = [ ([\"SEXUAL ABUSE 3,2\", \"SEXUAL ABUSE\", \"SODOMY 1\", \"RAPE 1\", \"RAPE 3\", \"RAPE 2\"], \"sexual assault\"), ([\"MURDER,UNCLASSIFIED\"], \"murder\"),\r\n ([\"ASSAULT 2,1,UNCLASSIFIED\", \"ASSAULT 3\"], \"aggravated assault\"), ([\"BURGLARY,UNCLASSIFIED,UNKNOWN\", \"BURGLARY,RESIDENCE,NIGHT\"], \"burglary\"),\r\n ([\"ROBBERY,OPEN AREA UNCLASSIFIED\"], \"robbery\"), ([\"LARCENY,GRAND FROM PERSON,UNCL\", \"LARCENY,GRAND FROM OPEN AREAS, UNATTENDED\", \"LARCENY,PETIT FROM OPEN AREAS,\"], \"theft\"),\r\n ([\"LARCENY,GRAND OF AUTO\"], \"motor vehicle theft\") ]\r\n\r\ncrime_type_fields = {\"Chicago\" : \"fbi_code\",\r\n \"Austin\" : \"ucr_category\",\r\n \"New York\" : \"pd_desc\"\r\n }\r\n\r\n\r\n","repo_name":"jackboller1/Tourist_Watch","sub_path":"crime_grouping.py","file_name":"crime_grouping.py","file_ext":"py","file_size_in_byte":1505,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"32258993407","text":"#!/usr/bin/python3\n\nimport sys;\nimport cgi;\nimport cgitb;\nimport os;\nimport cgicommon;\nimport urllib.request, urllib.parse, urllib.error;\nimport re;\n\ndef show_now_showing_frame(tourney):\n cgicommon.writeln(\"\" % (urllib.parse.quote_plus(tourney.get_name())))\n\ndef show_view_preview(tourney, form, selected_view):\n cgicommon.writeln(\"\" % (urllib.parse.quote_plus(tourney.get_name()), selected_view))\n\ncheckbox_to_assoc_field = {\n \"standings_videprinter_spell_big_scores\" : \"standings_videprinter_big_score_min\"\n}\n\nassoc_field_to_checkbox = {\n \"standings_videprinter_big_score_min\" : \"standings_videprinter_spell_big_scores\"\n}\n\ndef show_view_option_controls(tourney, form, options):\n if not options:\n return\n cgicommon.writeln(\"