davanstrien HF Staff commited on
Commit
702b604
·
verified ·
1 Parent(s): d710f26

Upload train_od.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. train_od.py +520 -0
train_od.py ADDED
@@ -0,0 +1,520 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # Copyright 2024 The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+
15
+ # /// script
16
+ # dependencies = [
17
+ # "transformers>=4.46,<5",
18
+ # "albumentations>=1.4.16",
19
+ # "timm",
20
+ # "datasets>=3.0",
21
+ # "torchmetrics>=1.4",
22
+ # "pycocotools",
23
+ # "torch>=2.1",
24
+ # "torchvision>=0.16",
25
+ # "numpy<2",
26
+ # ]
27
+ # ///
28
+
29
+ """Finetuning any 🤗 Transformers model supported by AutoModelForObjectDetection for object detection leveraging the Trainer API."""
30
+
31
+ import logging
32
+ import os
33
+ import sys
34
+ from collections.abc import Mapping
35
+ from dataclasses import dataclass, field
36
+ from functools import partial
37
+ from typing import Any
38
+
39
+ import albumentations as A
40
+ import numpy as np
41
+ import torch
42
+ from datasets import load_dataset
43
+ from torchmetrics.detection.mean_ap import MeanAveragePrecision
44
+
45
+ import transformers
46
+ from transformers import (
47
+ AutoConfig,
48
+ AutoImageProcessor,
49
+ AutoModelForObjectDetection,
50
+ HfArgumentParser,
51
+ Trainer,
52
+ TrainingArguments,
53
+ )
54
+ from transformers.image_processing_utils import BatchFeature
55
+ from transformers.image_transforms import center_to_corners_format
56
+ from transformers.trainer import EvalPrediction
57
+ from transformers.utils import check_min_version
58
+ from transformers.utils.versions import require_version
59
+
60
+
61
+ logger = logging.getLogger(__name__)
62
+
63
+ # Will error if the minimal version of Transformers is not installed. Remove at your own risks.
64
+
65
+
66
+ @dataclass
67
+ class ModelOutput:
68
+ logits: torch.Tensor
69
+ pred_boxes: torch.Tensor
70
+
71
+
72
+ def format_image_annotations_as_coco(
73
+ image_id: str, categories: list[int], areas: list[float], bboxes: list[tuple[float]]
74
+ ) -> dict:
75
+ """Format one set of image annotations to the COCO format
76
+
77
+ Args:
78
+ image_id (str): image id. e.g. "0001"
79
+ categories (list[int]): list of categories/class labels corresponding to provided bounding boxes
80
+ areas (list[float]): list of corresponding areas to provided bounding boxes
81
+ bboxes (list[tuple[float]]): list of bounding boxes provided in COCO format
82
+ ([center_x, center_y, width, height] in absolute coordinates)
83
+
84
+ Returns:
85
+ dict: {
86
+ "image_id": image id,
87
+ "annotations": list of formatted annotations
88
+ }
89
+ """
90
+ annotations = []
91
+ for category, area, bbox in zip(categories, areas, bboxes):
92
+ formatted_annotation = {
93
+ "image_id": image_id,
94
+ "category_id": category,
95
+ "iscrowd": 0,
96
+ "area": area,
97
+ "bbox": list(bbox),
98
+ }
99
+ annotations.append(formatted_annotation)
100
+
101
+ return {
102
+ "image_id": image_id,
103
+ "annotations": annotations,
104
+ }
105
+
106
+
107
+ def convert_bbox_yolo_to_pascal(boxes: torch.Tensor, image_size: tuple[int, int]) -> torch.Tensor:
108
+ """
109
+ Convert bounding boxes from YOLO format (x_center, y_center, width, height) in range [0, 1]
110
+ to Pascal VOC format (x_min, y_min, x_max, y_max) in absolute coordinates.
111
+
112
+ Args:
113
+ boxes (torch.Tensor): Bounding boxes in YOLO format
114
+ image_size (tuple[int, int]): Image size in format (height, width)
115
+
116
+ Returns:
117
+ torch.Tensor: Bounding boxes in Pascal VOC format (x_min, y_min, x_max, y_max)
118
+ """
119
+ # convert center to corners format
120
+ boxes = center_to_corners_format(boxes)
121
+
122
+ # convert to absolute coordinates
123
+ height, width = image_size
124
+ boxes = boxes * torch.tensor([[width, height, width, height]])
125
+
126
+ return boxes
127
+
128
+
129
+ def augment_and_transform_batch(
130
+ examples: Mapping[str, Any],
131
+ transform: A.Compose,
132
+ image_processor: AutoImageProcessor,
133
+ return_pixel_mask: bool = False,
134
+ ) -> BatchFeature:
135
+ """Apply augmentations and format annotations in COCO format for object detection task"""
136
+
137
+ images = []
138
+ annotations = []
139
+ for image_id, image, objects in zip(examples["image_id"], examples["image"], examples["objects"]):
140
+ image = np.array(image.convert("RGB"))
141
+
142
+ # apply augmentations
143
+ output = transform(image=image, bboxes=objects["bbox"], category=objects["category"])
144
+ images.append(output["image"])
145
+
146
+ # format annotations in COCO format
147
+ formatted_annotations = format_image_annotations_as_coco(
148
+ image_id, output["category"], objects["area"], output["bboxes"]
149
+ )
150
+ annotations.append(formatted_annotations)
151
+
152
+ # Apply the image processor transformations: resizing, rescaling, normalization
153
+ result = image_processor(images=images, annotations=annotations, return_tensors="pt")
154
+
155
+ if not return_pixel_mask:
156
+ result.pop("pixel_mask", None)
157
+
158
+ return result
159
+
160
+
161
+ def collate_fn(batch: list[BatchFeature]) -> Mapping[str, torch.Tensor | list[Any]]:
162
+ data = {}
163
+ data["pixel_values"] = torch.stack([x["pixel_values"] for x in batch])
164
+ data["labels"] = [x["labels"] for x in batch]
165
+ if "pixel_mask" in batch[0]:
166
+ data["pixel_mask"] = torch.stack([x["pixel_mask"] for x in batch])
167
+ return data
168
+
169
+
170
+ @torch.no_grad()
171
+ def compute_metrics(
172
+ evaluation_results: EvalPrediction,
173
+ image_processor: AutoImageProcessor,
174
+ threshold: float = 0.0,
175
+ id2label: Mapping[int, str] | None = None,
176
+ ) -> Mapping[str, float]:
177
+ """
178
+ Compute mean average mAP, mAR and their variants for the object detection task.
179
+
180
+ Args:
181
+ evaluation_results (EvalPrediction): Predictions and targets from evaluation.
182
+ threshold (float, optional): Threshold to filter predicted boxes by confidence. Defaults to 0.0.
183
+ id2label (Optional[dict], optional): Mapping from class id to class name. Defaults to None.
184
+
185
+ Returns:
186
+ Mapping[str, float]: Metrics in a form of dictionary {<metric_name>: <metric_value>}
187
+ """
188
+
189
+ predictions, targets = evaluation_results.predictions, evaluation_results.label_ids
190
+
191
+ # For metric computation we need to provide:
192
+ # - targets in a form of list of dictionaries with keys "boxes", "labels"
193
+ # - predictions in a form of list of dictionaries with keys "boxes", "scores", "labels"
194
+
195
+ image_sizes = []
196
+ post_processed_targets = []
197
+ post_processed_predictions = []
198
+
199
+ # Collect targets in the required format for metric computation
200
+ for batch in targets:
201
+ # collect image sizes, we will need them for predictions post processing
202
+ batch_image_sizes = torch.tensor([x["orig_size"] for x in batch])
203
+ image_sizes.append(batch_image_sizes)
204
+ # collect targets in the required format for metric computation
205
+ # boxes were converted to YOLO format needed for model training
206
+ # here we will convert them to Pascal VOC format (x_min, y_min, x_max, y_max)
207
+ for image_target in batch:
208
+ boxes = torch.tensor(image_target["boxes"])
209
+ boxes = convert_bbox_yolo_to_pascal(boxes, image_target["orig_size"])
210
+ labels = torch.tensor(image_target["class_labels"])
211
+ post_processed_targets.append({"boxes": boxes, "labels": labels})
212
+
213
+ # Collect predictions in the required format for metric computation,
214
+ # model produce boxes in YOLO format, then image_processor convert them to Pascal VOC format
215
+ for batch, target_sizes in zip(predictions, image_sizes):
216
+ batch_logits, batch_boxes = batch[1], batch[2]
217
+ output = ModelOutput(logits=torch.tensor(batch_logits), pred_boxes=torch.tensor(batch_boxes))
218
+ post_processed_output = image_processor.post_process_object_detection(
219
+ output, threshold=threshold, target_sizes=target_sizes
220
+ )
221
+ post_processed_predictions.extend(post_processed_output)
222
+
223
+ # Compute metrics
224
+ metric = MeanAveragePrecision(box_format="xyxy", class_metrics=True)
225
+ metric.update(post_processed_predictions, post_processed_targets)
226
+ metrics = metric.compute()
227
+
228
+ # Replace list of per class metrics with separate metric for each class
229
+ classes = metrics.pop("classes")
230
+ map_per_class = metrics.pop("map_per_class")
231
+ mar_100_per_class = metrics.pop("mar_100_per_class")
232
+ for class_id, class_map, class_mar in zip(classes, map_per_class, mar_100_per_class):
233
+ class_name = id2label[class_id.item()] if id2label is not None else class_id.item()
234
+ metrics[f"map_{class_name}"] = class_map
235
+ metrics[f"mar_100_{class_name}"] = class_mar
236
+
237
+ metrics = {k: round(v.item(), 4) for k, v in metrics.items()}
238
+
239
+ return metrics
240
+
241
+
242
+ @dataclass
243
+ class DataTrainingArguments:
244
+ """
245
+ Arguments pertaining to what data we are going to input our model for training and eval.
246
+ Using `HfArgumentParser` we can turn this class into argparse arguments to be able to specify
247
+ them on the command line.
248
+ """
249
+
250
+ dataset_name: str = field(
251
+ default="cppe-5",
252
+ metadata={
253
+ "help": "Name of a dataset from the hub (could be your own, possibly private dataset hosted on the hub)."
254
+ },
255
+ )
256
+ dataset_config_name: str | None = field(
257
+ default=None, metadata={"help": "The configuration name of the dataset to use (via the datasets library)."}
258
+ )
259
+ train_val_split: float | None = field(
260
+ default=0.15, metadata={"help": "Percent to split off of train for validation."}
261
+ )
262
+ image_square_size: int | None = field(
263
+ default=600,
264
+ metadata={"help": "Image longest size will be resized to this value, then image will be padded to square."},
265
+ )
266
+ max_train_samples: int | None = field(
267
+ default=None,
268
+ metadata={
269
+ "help": (
270
+ "For debugging purposes or quicker training, truncate the number of training examples to this "
271
+ "value if set."
272
+ )
273
+ },
274
+ )
275
+ max_eval_samples: int | None = field(
276
+ default=None,
277
+ metadata={
278
+ "help": (
279
+ "For debugging purposes or quicker training, truncate the number of evaluation examples to this "
280
+ "value if set."
281
+ )
282
+ },
283
+ )
284
+ use_fast: bool | None = field(
285
+ default=True,
286
+ metadata={"help": "Use a fast torchvision-base image processor if it is supported for a given model."},
287
+ )
288
+
289
+
290
+ @dataclass
291
+ class ModelArguments:
292
+ """
293
+ Arguments pertaining to which model/config/tokenizer we are going to fine-tune from.
294
+ """
295
+
296
+ model_name_or_path: str = field(
297
+ default="facebook/detr-resnet-50",
298
+ metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"},
299
+ )
300
+ config_name: str | None = field(
301
+ default=None, metadata={"help": "Pretrained config name or path if not the same as model_name"}
302
+ )
303
+ cache_dir: str | None = field(
304
+ default=None, metadata={"help": "Where do you want to store the pretrained models downloaded from s3"}
305
+ )
306
+ model_revision: str = field(
307
+ default="main",
308
+ metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."},
309
+ )
310
+ image_processor_name: str = field(default=None, metadata={"help": "Name or path of preprocessor config."})
311
+ ignore_mismatched_sizes: bool = field(
312
+ default=False,
313
+ metadata={
314
+ "help": "Whether or not to raise an error if some of the weights from the checkpoint do not have the same size as the weights of the model (if for instance, you are instantiating a model with 10 labels from a checkpoint with 3 labels)."
315
+ },
316
+ )
317
+ token: str = field(
318
+ default=None,
319
+ metadata={
320
+ "help": (
321
+ "The token to use as HTTP bearer authorization for remote files. If not specified, will use the token "
322
+ "generated when running `hf auth login` (stored in `~/.huggingface`)."
323
+ )
324
+ },
325
+ )
326
+ trust_remote_code: bool = field(
327
+ default=False,
328
+ metadata={
329
+ "help": (
330
+ "Whether to trust the execution of code from datasets/models defined on the Hub."
331
+ " This option should only be set to `True` for repositories you trust and in which you have read the"
332
+ " code, as it will execute code present on the Hub on your local machine."
333
+ )
334
+ },
335
+ )
336
+
337
+
338
+ def main():
339
+ # See all possible arguments in src/transformers/training_args.py
340
+ # or by passing the --help flag to this script.
341
+ # We now keep distinct sets of args, for a cleaner separation of concerns.
342
+
343
+ parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments))
344
+ if len(sys.argv) == 2 and sys.argv[1].endswith(".json"):
345
+ # If we pass only one argument to the script and it's the path to a json file,
346
+ # let's parse it to get our arguments.
347
+ model_args, data_args, training_args = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]))
348
+ else:
349
+ model_args, data_args, training_args = parser.parse_args_into_dataclasses()
350
+
351
+ # Setup logging
352
+ logging.basicConfig(
353
+ format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
354
+ datefmt="%m/%d/%Y %H:%M:%S",
355
+ handlers=[logging.StreamHandler(sys.stdout)],
356
+ )
357
+
358
+ if training_args.should_log:
359
+ # The default of training_args.log_level is passive, so we set log level at info here to have that default.
360
+ transformers.utils.logging.set_verbosity_info()
361
+
362
+ log_level = training_args.get_process_log_level()
363
+ logger.setLevel(log_level)
364
+ transformers.utils.logging.set_verbosity(log_level)
365
+ transformers.utils.logging.enable_default_handler()
366
+ transformers.utils.logging.enable_explicit_format()
367
+
368
+ # Log on each process the small summary:
369
+ logger.warning(
370
+ f"Process rank: {training_args.local_process_index}, device: {training_args.device}, n_gpu: {training_args.n_gpu}, "
371
+ + f"distributed training: {training_args.parallel_mode.value == 'distributed'}, 16-bits training: {training_args.fp16}"
372
+ )
373
+ logger.info(f"Training/evaluation parameters {training_args}")
374
+
375
+ # ------------------------------------------------------------------------------------------------
376
+ # Load dataset, prepare splits
377
+ # ------------------------------------------------------------------------------------------------
378
+
379
+ dataset = load_dataset(
380
+ data_args.dataset_name, cache_dir=model_args.cache_dir, trust_remote_code=model_args.trust_remote_code
381
+ )
382
+
383
+ # If we don't have a validation split, split off a percentage of train as validation
384
+ data_args.train_val_split = None if "validation" in dataset else data_args.train_val_split
385
+ if isinstance(data_args.train_val_split, float) and data_args.train_val_split > 0.0:
386
+ split = dataset["train"].train_test_split(data_args.train_val_split, seed=training_args.seed)
387
+ dataset["train"] = split["train"]
388
+ dataset["validation"] = split["test"]
389
+
390
+ # Get dataset categories and prepare mappings for label_name <-> label_id
391
+ if isinstance(dataset["train"].features["objects"], dict):
392
+ categories = dataset["train"].features["objects"]["category"].feature.names
393
+ else: # (for old versions of `datasets` that used Sequence({...}) of the objects)
394
+ categories = dataset["train"].features["objects"].feature["category"].names
395
+ id2label = dict(enumerate(categories))
396
+ label2id = {v: k for k, v in id2label.items()}
397
+
398
+ # ------------------------------------------------------------------------------------------------
399
+ # Load pretrained config, model and image processor
400
+ # ------------------------------------------------------------------------------------------------
401
+
402
+ common_pretrained_args = {
403
+ "cache_dir": model_args.cache_dir,
404
+ "revision": model_args.model_revision,
405
+ "token": model_args.token,
406
+ "trust_remote_code": model_args.trust_remote_code,
407
+ }
408
+ config = AutoConfig.from_pretrained(
409
+ model_args.config_name or model_args.model_name_or_path,
410
+ label2id=label2id,
411
+ id2label=id2label,
412
+ **common_pretrained_args,
413
+ )
414
+ model = AutoModelForObjectDetection.from_pretrained(
415
+ model_args.model_name_or_path,
416
+ config=config,
417
+ ignore_mismatched_sizes=model_args.ignore_mismatched_sizes,
418
+ **common_pretrained_args,
419
+ )
420
+ image_processor = AutoImageProcessor.from_pretrained(
421
+ model_args.image_processor_name or model_args.model_name_or_path,
422
+ do_resize=True,
423
+ size={"max_height": data_args.image_square_size, "max_width": data_args.image_square_size},
424
+ do_pad=True,
425
+ pad_size={"height": data_args.image_square_size, "width": data_args.image_square_size},
426
+ use_fast=data_args.use_fast,
427
+ **common_pretrained_args,
428
+ )
429
+
430
+ # ------------------------------------------------------------------------------------------------
431
+ # Define image augmentations and dataset transforms
432
+ # ------------------------------------------------------------------------------------------------
433
+ max_size = data_args.image_square_size
434
+ train_augment_and_transform = A.Compose(
435
+ [
436
+ A.Compose(
437
+ [
438
+ A.SmallestMaxSize(max_size=max_size, p=1.0),
439
+ A.RandomSizedBBoxSafeCrop(height=max_size, width=max_size, p=1.0),
440
+ ],
441
+ p=0.2,
442
+ ),
443
+ A.OneOf(
444
+ [
445
+ A.Blur(blur_limit=7, p=0.5),
446
+ A.MotionBlur(blur_limit=7, p=0.5),
447
+ A.Defocus(radius=(1, 5), alias_blur=(0.1, 0.25), p=0.1),
448
+ ],
449
+ p=0.1,
450
+ ),
451
+ A.Perspective(p=0.1),
452
+ A.HorizontalFlip(p=0.5),
453
+ A.RandomBrightnessContrast(p=0.5),
454
+ A.HueSaturationValue(p=0.1),
455
+ ],
456
+ bbox_params=A.BboxParams(format="coco", label_fields=["category"], clip=True, min_area=25),
457
+ )
458
+ validation_transform = A.Compose(
459
+ [A.NoOp()],
460
+ bbox_params=A.BboxParams(format="coco", label_fields=["category"], clip=True),
461
+ )
462
+
463
+ # Make transform functions for batch and apply for dataset splits
464
+ train_transform_batch = partial(
465
+ augment_and_transform_batch, transform=train_augment_and_transform, image_processor=image_processor
466
+ )
467
+ validation_transform_batch = partial(
468
+ augment_and_transform_batch, transform=validation_transform, image_processor=image_processor
469
+ )
470
+
471
+ dataset["train"] = dataset["train"].with_transform(train_transform_batch)
472
+ dataset["validation"] = dataset["validation"].with_transform(validation_transform_batch)
473
+ dataset["test"] = dataset["test"].with_transform(validation_transform_batch)
474
+
475
+ # ------------------------------------------------------------------------------------------------
476
+ # Model training and evaluation with Trainer API
477
+ # ------------------------------------------------------------------------------------------------
478
+
479
+ eval_compute_metrics_fn = partial(
480
+ compute_metrics, image_processor=image_processor, id2label=id2label, threshold=0.0
481
+ )
482
+
483
+ trainer = Trainer(
484
+ model=model,
485
+ args=training_args,
486
+ train_dataset=dataset["train"] if training_args.do_train else None,
487
+ eval_dataset=dataset["validation"] if training_args.do_eval else None,
488
+ processing_class=image_processor,
489
+ data_collator=collate_fn,
490
+ compute_metrics=eval_compute_metrics_fn,
491
+ )
492
+
493
+ # Training
494
+ if training_args.do_train:
495
+ train_result = trainer.train(resume_from_checkpoint=training_args.resume_from_checkpoint)
496
+ trainer.save_model()
497
+ trainer.log_metrics("train", train_result.metrics)
498
+ trainer.save_metrics("train", train_result.metrics)
499
+ trainer.save_state()
500
+
501
+ # Final evaluation
502
+ if training_args.do_eval:
503
+ metrics = trainer.evaluate(eval_dataset=dataset["test"], metric_key_prefix="test")
504
+ trainer.log_metrics("test", metrics)
505
+ trainer.save_metrics("test", metrics)
506
+
507
+ # Write model card and (optionally) push to hub
508
+ kwargs = {
509
+ "finetuned_from": model_args.model_name_or_path,
510
+ "dataset": data_args.dataset_name,
511
+ "tags": ["object-detection", "vision"],
512
+ }
513
+ if training_args.push_to_hub:
514
+ trainer.push_to_hub(**kwargs)
515
+ else:
516
+ trainer.create_model_card(**kwargs)
517
+
518
+
519
+ if __name__ == "__main__":
520
+ main()