internlm/SWE-Fixer-Train-110K huggingface dataset:
Repository: open-mmlab/mmpretrain

Issue:
mmcls/models/losses/eval_metrics.py confusion_matrix
confusion_matrix[target_label.long(), pred_label.long()] += 1
I think this code is wrong, 【target_label.long(), pred_label.long()】 will list all the coordinates that need + 1, but only once + 1 will work
it should be:
`for t, p in zip(target_label, pred_label):
           confusion_matrix[t.long(), p.long()] += 1 `



Discussion:

Resolving patch:
diff --git a/mmcls/models/losses/eval_metrics.py b/mmcls/models/losses/eval_metrics.py
--- a/mmcls/models/losses/eval_metrics.py
+++ b/mmcls/models/losses/eval_metrics.py
@@ -17,7 +17,8 @@ def calculate_confusion_matrix(pred, target):
     assert len(pred_label) == len(target_label)
     confusion_matrix = torch.zeros(num_classes, num_classes)
     with torch.no_grad():
-        confusion_matrix[target_label.long(), pred_label.long()] += 1
+        for t, p in zip(target_label, pred_label):
+            confusion_matrix[t.long(), p.long()] += 1
     return confusion_matrix
 
 


Test patch:
diff --git a/tests/test_dataset.py b/tests/test_dataset.py
--- a/tests/test_dataset.py
+++ b/tests/test_dataset.py
@@ -65,22 +65,23 @@ def test_datasets_override_default(dataset_name):
 def test_dataset_evaluation():
     dataset = BaseDataset(data_prefix='', pipeline=[], test_mode=True)
     dataset.data_infos = [
+        dict(gt_label=0),
         dict(gt_label=0),
         dict(gt_label=1),
         dict(gt_label=2),
         dict(gt_label=1),
         dict(gt_label=0)
     ]
-    fake_results = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1], [0, 0, 1],
-                             [0, 0, 1]])
+    fake_results = np.array([[1, 0, 0], [1, 0, 0], [0, 1, 0], [0, 0, 1],
+                             [0, 0, 1], [0, 0, 1]])
     eval_results = dataset.evaluate(
         fake_results, metric=['precision', 'recall', 'f1_score'])
     assert eval_results['precision'] == pytest.approx(
         (1 + 1 + 1 / 3) / 3 * 100.0)
     assert eval_results['recall'] == pytest.approx(
-        (1 / 2 + 1 / 2 + 1) / 3 * 100.0)
+        (2 / 3 + 1 / 2 + 1) / 3 * 100.0)
     assert eval_results['f1_score'] == pytest.approx(
-        (2 / 3 + 2 / 3 + 1 / 2) / 3 * 100.0)
+        (4 / 5 + 2 / 3 + 1 / 2) / 3 * 100.0)
 
 
 @patch.multiple(BaseDataset, __abstractmethods__=set())
Repository: open-mmlab/mmpretrain

Issue:
KeyError: 'LinearHead is not in the head registry'
use config
```python
model = dict(
    head=dict(
        type='LinearHead',
        num_classes=1000,
        in_channels=2048,
        loss=dict(
            type='LabelSmoothLoss',
            loss_weight=1.0,
            label_smooth_val=0.1,
            num_classes=1000),
    ))
```

got trackback
```python
Traceback (most recent call last):
  File "/home/code/open_mmlab_codebase/huatian_bump_blur_cls/tools/train.py", line 177, in <module>
    main()
  File "/home/code/open_mmlab_codebase/huatian_bump_blur_cls/tools/train.py", line 151, in main
    model = build_classifier(cfg.model)
  File "/home/code/open_mmlab_codebase/mmclassification/mmcls/models/builder.py", line 38, in build_classifier
    return build(cfg, CLASSIFIERS)
  File "/home/code/open_mmlab_codebase/mmclassification/mmcls/models/builder.py", line 18, in build
    return build_from_cfg(cfg, registry, default_args)
  File "/opt/conda/lib/python3.7/site-packages/mmcv/utils/registry.py", line 171, in build_from_cfg
    return obj_cls(**args)
  File "/home/code/open_mmlab_codebase/mmclassification/mmcls/models/classifiers/image.py", line 18, in __init__
    self.head = build_head(head)
  File "/home/code/open_mmlab_codebase/mmclassification/mmcls/models/builder.py", line 26, in build_head
    return build(cfg, HEADS)
  File "/home/code/open_mmlab_codebase/mmclassification/mmcls/models/builder.py", line 18, in build
    return build_from_cfg(cfg, registry, default_args)
  File "/opt/conda/lib/python3.7/site-packages/mmcv/utils/registry.py", line 164, in build_from_cfg
    f'{obj_type} is not in the {registry.name} registry')
KeyError: 'LinearHead is not in the head registry'
```

__check /mmcls/models/heads/*.py, not exist `LinearHead` registered__


Discussion:
it is a typo? i change type from `LinearHead` to `LinearClsHead`, it works!
It seems to be. Feel free to submit a pull request for this bug. 

Resolving patch:
diff --git a/configs/resnet/resnet50_b32x8_label_smooth_imagenet.py b/configs/resnet/resnet50_b32x8_label_smooth_imagenet.py
--- a/configs/resnet/resnet50_b32x8_label_smooth_imagenet.py
+++ b/configs/resnet/resnet50_b32x8_label_smooth_imagenet.py
@@ -1,7 +1,7 @@
 _base_ = ['./resnet50_imagenet_bs256.py']
 model = dict(
     head=dict(
-        type='LinearHead',
+        type='LinearClsHead',
         num_classes=1000,
         in_channels=2048,
         loss=dict(
diff --git a/configs/resnet/resnet50_b64x32_warmup_label_smooth_imagenet.py b/configs/resnet/resnet50_b64x32_warmup_label_smooth_imagenet.py
--- a/configs/resnet/resnet50_b64x32_warmup_label_smooth_imagenet.py
+++ b/configs/resnet/resnet50_b64x32_warmup_label_smooth_imagenet.py
@@ -1,7 +1,7 @@
 _base_ = ['./resnet50_batch2048_warmup.py']
 model = dict(
     head=dict(
-        type='LinearHead',
+        type='LinearClsHead',
         num_classes=1000,
         in_channels=2048,
         loss=dict(


Test patch:
Repository: open-mmlab/mmpretrain

Issue:
bug report
The attribute **meta_keys** is lost in Collect.
```python
@PIPELINES.register_module()
class Collect(object):
    """
    Collect data from the loader relevant to the specific task.
    This is usually the last stage of the data loader pipeline. Typically keys
    is set to some subset of "img" and "gt_label".
    """

    def __init__(self, keys):
        self.keys = keys

    def __call__(self, results):
        data = {}
        for key in self.keys:
            data[key] = results[key]
        return data

    def __repr__(self):
        return self.__class__.__name__ + \
            f'(keys={self.keys}, meta_keys={self.meta_keys})'
```


Discussion:
Thanks for reporting this bug, we'll fix it soon.

Resolving patch:
diff --git a/mmcls/datasets/pipelines/formating.py b/mmcls/datasets/pipelines/formating.py
--- a/mmcls/datasets/pipelines/formating.py
+++ b/mmcls/datasets/pipelines/formating.py
@@ -3,6 +3,7 @@
 import mmcv
 import numpy as np
 import torch
+from mmcv.parallel import DataContainer as DC
 from PIL import Image
 
 from ..builder import PIPELINES
@@ -110,13 +111,34 @@ class Collect(object):
 
     This is usually the last stage of the data loader pipeline. Typically keys
     is set to some subset of "img" and "gt_label".
+
+    Args:
+        keys (Sequence[str]): Keys of results to be collected in ``data``.
+        meta_keys (Sequence[str], optional): Meta keys to be converted to
+            ``mmcv.DataContainer`` and collected in ``data[img_metas]``.
+            Default: ``('filename', 'ori_shape', 'img_shape', 'flip',
+            'flip_direction', 'img_norm_cfg')``
+
+    Returns:
+        dict: The result dict contains the following keys
+                - keys in``self.keys``
+                - ``img_metas`` if avaliable
     """
 
-    def __init__(self, keys):
+    def __init__(self,
+                 keys,
+                 meta_keys=('filename', 'ori_shape', 'img_shape', 'flip',
+                            'flip_direction', 'img_norm_cfg')):
         self.keys = keys
+        self.meta_keys = meta_keys
 
     def __call__(self, results):
         data = {}
+        img_meta = {}
+        for key in self.meta_keys:
+            if key in results:
+                img_meta[key] = results[key]
+        data['img_metas'] = DC(img_meta, cpu_only=True)
         for key in self.keys:
             data[key] = results[key]
         return data


Test patch:
Repository: open-mmlab/mmpretrain

Issue:
[Feature Request] CPU Testing
Since CPU training is already supported in PR #219, what about also adding the feature of CPU testing. 

Besides, it seems there are still some problems with the CPU training feature @wangruohui : 
When we set `--device CPU`, the expected behavior is using CPU for training, no matter if there exist GPUs on this machine. However, mmcls will use GPU for training if it exists, even if we set `--device CPU`. 


Discussion:

Resolving patch:
diff --git a/mmcls/apis/train.py b/mmcls/apis/train.py
--- a/mmcls/apis/train.py
+++ b/mmcls/apis/train.py
@@ -87,7 +87,7 @@ def train_model(model,
             model = MMDataParallel(
                 model.cuda(cfg.gpu_ids[0]), device_ids=cfg.gpu_ids)
         elif device == 'cpu':
-            model = MMDataParallel(model.cpu())
+            model = model.cpu()
         else:
             raise ValueError(F'unsupported device name {device}.')
 


Test patch:
diff --git a/tools/test.py b/tools/test.py
--- a/tools/test.py
+++ b/tools/test.py
@@ -69,6 +69,11 @@ def parse_args():
         default='none',
         help='job launcher')
     parser.add_argument('--local_rank', type=int, default=0)
+    parser.add_argument(
+        '--device',
+        choices=['cpu', 'cuda'],
+        default='cuda',
+        help='device used for testing')
     args = parser.parse_args()
     if 'LOCAL_RANK' not in os.environ:
         os.environ['LOCAL_RANK'] = str(args.local_rank)
@@ -121,7 +126,10 @@ def main():
         CLASSES = ImageNet.CLASSES
 
     if not distributed:
-        model = MMDataParallel(model, device_ids=[0])
+        if args.device == 'cpu':
+            model = model.cpu()
+        else:
+            model = MMDataParallel(model, device_ids=[0])
         model.CLASSES = CLASSES
         show_kwargs = {} if args.show_options is None else args.show_options
         outputs = single_gpu_test(model, data_loader, args.show, args.show_dir,
Repository: open-mmlab/mmpretrain

Issue:
[Bug] The precision are not aligned between val during train and test 
### Branch

master branch (0.24 or other 0.x version)

### Describe the bug

The precision of val in the train is 73, and the precision of test 76, they are not aligned



### Environment

A100 or NPU

### Other information

_No response_


Discussion:
Please provide the detailed config file and log for better understanding.

Resolving patch:
diff --git a/mmcls/models/heads/multi_label_head.py b/mmcls/models/heads/multi_label_head.py
--- a/mmcls/models/heads/multi_label_head.py
+++ b/mmcls/models/heads/multi_label_head.py
@@ -82,7 +82,8 @@ def simple_test(self, x, sigmoid=True, post_process=True):
             x = x[-1]
 
         if sigmoid:
-            pred = torch.sigmoid(x) if x is not None else None
+            # Convert to full precision because sigmoid is sensitive.
+            pred = torch.sigmoid(x.float()) if x is not None else None
         else:
             pred = x
 
diff --git a/mmcls/models/heads/multi_label_linear_head.py b/mmcls/models/heads/multi_label_linear_head.py
--- a/mmcls/models/heads/multi_label_linear_head.py
+++ b/mmcls/models/heads/multi_label_linear_head.py
@@ -75,7 +75,9 @@ def simple_test(self, x, sigmoid=True, post_process=True):
         cls_score = self.fc(x)
 
         if sigmoid:
-            pred = torch.sigmoid(cls_score) if cls_score is not None else None
+            # Convert to full precision because sigmoid is sensitive.
+            pred = torch.sigmoid(
+                cls_score.float()) if cls_score is not None else None
         else:
             pred = cls_score
 


Test patch:
Repository: coqui-ai/TTS

Issue:
[Bug] Unable to initialize a LibriTTS Dataset with the Python Trainer API?
When setting up LibriTTS with dataset_config = BaseDatasetConfig(name="libri_tts", path=os.path.join(output_path, "../LibriTTS/train-clean-100/")), I get this error:

Traceback (most recent call last):
  File "train_fast_speech.py", line 78, in <module>
    train_samples, eval_samples = load_tts_samples(dataset_config, eval_split=True)
  File "/home/workstation/.local/lib/python3.8/site-packages/TTS/tts/datasets/__init__.py", line 111, in load_tts_samples
    meta_data_train = formatter(root_path, meta_file_train, ignored_speakers=ignored_speakers)
  File "/home/workstation/.local/lib/python3.8/site-packages/TTS/tts/datasets/formatters.py", line 249, in libri_tts
    assert os.path.exists(item[1]), f" [!] wav files don't exist - {item[1]}"
KeyError: 1
I placed the LibriTTS folder on branch up of the trainer script(exit one folder, and placed the LibriTTS dataset folder there), so I am not sure why it is not working.


Discussion:
Opened a Pull Request with fix: #1386

Resolving patch:
diff --git a/TTS/tts/datasets/formatters.py b/TTS/tts/datasets/formatters.py
--- a/TTS/tts/datasets/formatters.py
+++ b/TTS/tts/datasets/formatters.py
@@ -246,7 +246,7 @@ def libri_tts(root_path, meta_files=None, ignored_speakers=None):
                         continue
                 items.append({"text": text, "audio_file": wav_file, "speaker_name": f"LTTS_{speaker_name}"})
     for item in items:
-        assert os.path.exists(item[1]), f" [!] wav files don't exist - {item[1]}"
+        assert os.path.exists(item["audio_file"]), f" [!] wav files don't exist - {item['audio_file']}"
     return items
 
 


Test patch:
Repository: coqui-ai/TTS

Issue:
Missing `f` prefix on f-strings
Some strings looks like they're meant to be f-strings but are missing the `f` prefix meaning variable interpolation won't happen.

https://github.com/coqui-ai/TTS/blob/c410bc58ef3bd07b72ab05d29bbdc2a6df47afea/TTS/tts/layers/tacotron/attentions.py#L487

I found this issue automatically. I'm a bot. Beep Boop 🦊. See other issues I found in your repo [here](https://codereview.doctor/coqui-ai/TTS)


Discussion:

Resolving patch:
diff --git a/TTS/tts/layers/tacotron/attentions.py b/TTS/tts/layers/tacotron/attentions.py
--- a/TTS/tts/layers/tacotron/attentions.py
+++ b/TTS/tts/layers/tacotron/attentions.py
@@ -484,4 +484,4 @@ def init_attn(
             beta=0.9,
         )
 
-    raise RuntimeError(" [!] Given Attention Type '{attn_type}' is not exist.")
+    raise RuntimeError(f" [!] Given Attention Type '{attn_type}' is not exist.")


Test patch:
Repository: coqui-ai/TTS

Issue:
[Bug] Error in the definition of the function that adv loss in the vocoder.
### Describe the bug

[There](https://github.com/coqui-ai/TTS/blob/dev/TTS/vocoder/layers/losses.py#L200) is a simple bug here, `real_loss` and `fake_loss` will be overwritten instead of being cumulative, which will result in the `real_loss` and `fake_loss` in the return value being related only to the last discriminator.

### To Reproduce

It's a simple mistake that doesn't need to be reproduced.

### Expected behavior

_No response_

### Logs

_No response_

### Environment

```shell
No environmental description needed
```


### Additional context

_No response_


Discussion:
That is a perfect catch. You are awesome @jiaweiru !

Resolving patch:
diff --git a/TTS/vocoder/layers/losses.py b/TTS/vocoder/layers/losses.py
--- a/TTS/vocoder/layers/losses.py
+++ b/TTS/vocoder/layers/losses.py
@@ -195,10 +195,10 @@ def _apply_D_loss(scores_fake, scores_real, loss_func):
     if isinstance(scores_fake, list):
         # multi-scale loss
         for score_fake, score_real in zip(scores_fake, scores_real):
-            total_loss, real_loss, fake_loss = loss_func(score_fake=score_fake, score_real=score_real)
+            total_loss, real_loss_, fake_loss_ = loss_func(score_fake=score_fake, score_real=score_real)
             loss += total_loss
-            real_loss += real_loss
-            fake_loss += fake_loss
+            real_loss += real_loss_
+            fake_loss += fake_loss_
         # normalize loss values with number of scales (discriminators)
         loss /= len(scores_fake)
         real_loss /= len(scores_real)


Test patch:
Repository: coqui-ai/TTS

Issue:
[Bug] css10 formatter doesn't set the root_path attribute 
### Describe the bug

css10 formatter doesn't set the root_path attribute 
https://github.com/coqui-ai/TTS/blob/b5cd6441328fd9569f370d51a2449d09d546d335/TTS/tts/datasets/formatters.py#L244C95-L244C95

### To Reproduce

python -m trainer.distribute --script path/train_vits.py



### Expected behavior

_No response_

### Logs

_No response_

### Environment

```shell
TTS=0.15.6
```


### Additional context

_No response_


Discussion:
This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions. You might also look our discussion channels.


Resolving patch:
diff --git a/TTS/tts/datasets/formatters.py b/TTS/tts/datasets/formatters.py
--- a/TTS/tts/datasets/formatters.py
+++ b/TTS/tts/datasets/formatters.py
@@ -280,7 +280,7 @@ def css10(root_path, meta_file, **kwargs):  # pylint: disable=unused-argument
             cols = line.split("|")
             wav_file = os.path.join(root_path, cols[0])
             text = cols[1]
-            items.append({"text": text, "audio_file": wav_file, "speaker_name": speaker_name})
+            items.append({"text": text, "audio_file": wav_file, "speaker_name": speaker_name, "root_path": root_path})
     return items
 
 
@@ -294,7 +294,7 @@ def nancy(root_path, meta_file, **kwargs):  # pylint: disable=unused-argument
             utt_id = line.split()[1]
             text = line[line.find('"') + 1 : line.rfind('"') - 1]
             wav_file = os.path.join(root_path, "wavn", utt_id + ".wav")
-            items.append({"text": text, "audio_file": wav_file, "speaker_name": speaker_name})
+            items.append({"text": text, "audio_file": wav_file, "speaker_name": speaker_name, "root_path": root_path})
     return items
 
 


Test patch:
Repository: 3cn-ecn/nantralPlatform

Issue:
Frontend events planifés et events archivés ne fonctionnent pas
Events archivés renvoit une erreur 500.
Event planifiés ne renvoit rien


Discussion:

Resolving patch:
diff --git a/server/apps/event/api_views.py b/server/apps/event/api_views.py
--- a/server/apps/event/api_views.py
+++ b/server/apps/event/api_views.py
@@ -15,7 +15,7 @@ def get_queryset(self):
         if self.request.method == 'GET':
             if self.request.GET.get('view') == 'archives':
                 return BaseEvent.objects.filter(group=self.kwargs['group'], date__lt=datetime.today())
-            elif self.request.get('view') == 'all':
+            elif self.request.GET.get('view') == 'all':
                 return BaseEvent.objects.filter(group=self.kwargs['group'])
         return BaseEvent.objects.filter(group=self.kwargs['group'], date__gte=datetime.today())
 
diff --git a/server/apps/event/views.py b/server/apps/event/views.py
--- a/server/apps/event/views.py
+++ b/server/apps/event/views.py
@@ -91,13 +91,13 @@ def post(self, request,  group_slug):
 
 
 class UpdateGroupArchivedEventsView(UserIsAdmin, View):
-    template_name = 'group/archived_edit.html'
+    template_name = 'group/event/archived_edit.html'
 
     def get_context_data(self, **kwargs):
         context = {}
         context['object'] = Group.get_group_by_slug(kwargs['group_slug'])
         context['events'] = BaseEvent.objects.filter(
-            group=kwargs['group_slug'], date__lt=date.today())
+            group=kwargs['group_slug'], date__lte=date.today())
         context['form'] = EventFormSet(queryset=context['events'])
         return context
 


Test patch:
Repository: 3cn-ecn/nantralPlatform

Issue:
Problème avec les liens vers les auteur.ic.es des suggestions
Quand quelqu'un fait une suggestion depuis le site, le lien pour avoir le nom de la personne ne fonctionne pas.


Discussion:

Resolving patch:
diff --git a/server/apps/home/forms.py b/server/apps/home/forms.py
--- a/server/apps/home/forms.py
+++ b/server/apps/home/forms.py
@@ -1,5 +1,14 @@
 from django import forms
 
+TYPE_CHOICES = (
+    (1, ("Bug")),
+    (2, ("Suggestion"))
+)
+
+
 class SuggestionForm(forms.Form):
     title = forms.CharField(max_length=50, required=True)
     description = forms.CharField(widget=forms.Textarea)
+    suggestionOrBug = forms.ChoiceField(label="Type",
+                                        choices=TYPE_CHOICES,
+                                        required=True)
diff --git a/server/apps/home/views.py b/server/apps/home/views.py
--- a/server/apps/home/views.py
+++ b/server/apps/home/views.py
@@ -34,7 +34,8 @@ class SuggestionView(LoginRequiredMixin, FormView):
     def form_valid(self, form):
         create_issue(
             title=form.cleaned_data['title'],
-            body=f"{form.cleaned_data['description']} <br/> <a href='http://{get_current_site(self.request)}{self.request.user.student.get_absolute_url}'>Clique pour découvrir qui propose ça.</a>"
+            body=f"{form.cleaned_data['description']} <br/> [Clique pour découvrir qui propose ça.](http://{get_current_site(self.request)}{self.request.user.student.get_absolute_url()})",
+            label=form.cleaned_data['suggestionOrBug']
         )
         messages.success(
             self.request, 'Votre suggestion a été enregistrée merci')
diff --git a/server/apps/utils/github.py b/server/apps/utils/github.py
--- a/server/apps/utils/github.py
+++ b/server/apps/utils/github.py
@@ -2,15 +2,18 @@
 from django.conf import settings
 
 
-def create_issue(title: str, body: str):
+def create_issue(title: str, body: str, label):
+    label = "bug" if int(label) == 1 else "suggestion"
     issue = {
         'title': title,
-        'body': body
+        'body': body,
+        'labels': [label]
     }
     resp = requests.post(f'https://api.github.com/repos/{settings.GITHUB_REPO}/issues',
                          json=issue, auth=(settings.GITHUB_USER, settings.GITHUB_TOKEN))
     if resp.status_code != 201:
-        raise Exception(f'Error while posting issue to Github: {resp.reason}')
+        raise Exception(
+            f'Error while posting issue to Github: {resp.reason}')
     return resp.json()['number']
 
 


Test patch: