anon-iclr-submission/benchname-bug-localization huggingface dataset:
Repository: getmoto/moto
Issue: Cognito Identity identity_id format should be in format `REGION:GUID`

Hi

Running tests using moto revealed issue with the _identity id_ gotten from `cognitoidentity`. In reality aws _identity_ids_ should be `REGION:GUID`.[0] However moto creates an _identity id_ in format `"{0}:{1}".format(region, get_random_hex(length=19))`. [1] This causes issues when being strict with what the format is expected to be.

[0] https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/cognito-identity.html#CognitoIdentity.Client.get_id
[1] https://github.com/spulec/moto/blob/master/moto/cognitoidentity/utils.py

Changed files:
tests/test_cognitoidentity/test_cognitoidentity.py, moto/cognitoidentity/utils.py, tests/test_cognitoidentity/test_server.py

diff --git a/moto/cognitoidentity/utils.py b/moto/cognitoidentity/utils.py
index 6143d5121..54016ad17 100644
--- a/moto/cognitoidentity/utils.py
+++ b/moto/cognitoidentity/utils.py
@@ -1,5 +1,5 @@
-from moto.core.utils import get_random_hex
+from uuid import uuid4
 
 
 def get_random_identity_id(region):
-    return "{0}:{1}".format(region, get_random_hex(length=19))
+    return "{0}:{1}".format(region, uuid4())
diff --git a/tests/test_cognitoidentity/test_cognitoidentity.py b/tests/test_cognitoidentity/test_cognitoidentity.py
index 8eae183c6..0ec7acfb0 100644
--- a/tests/test_cognitoidentity/test_cognitoidentity.py
+++ b/tests/test_cognitoidentity/test_cognitoidentity.py
@@ -7,6 +7,7 @@ from nose.tools import assert_raises
 from moto import mock_cognitoidentity
 from moto.cognitoidentity.utils import get_random_identity_id
 from moto.core import ACCOUNT_ID
+from uuid import UUID
 
 
 @mock_cognitoidentity
@@ -83,8 +84,10 @@ def test_describe_identity_pool_with_invalid_id_raises_error():
 
 # testing a helper function
 def test_get_random_identity_id():
-    assert len(get_random_identity_id("us-west-2")) > 0
-    assert len(get_random_identity_id("us-west-2").split(":")[1]) == 19
+    identity_id = get_random_identity_id("us-west-2")
+    region, id = identity_id.split(":")
+    region.should.equal("us-west-2")
+    UUID(id, version=4)  # Will throw an error if it's not a valid UUID
 
 
 @mock_cognitoidentity
@@ -96,7 +99,6 @@ def test_get_id():
         IdentityPoolId="us-west-2:12345",
         Logins={"someurl": "12345"},
     )
-    print(result)
     assert (
         result.get("IdentityId", "").startswith("us-west-2")
         or result.get("ResponseMetadata").get("HTTPStatusCode") == 200
diff --git a/tests/test_cognitoidentity/test_server.py b/tests/test_cognitoidentity/test_server.py
index 903dae290..8c4229f06 100644
--- a/tests/test_cognitoidentity/test_server.py
+++ b/tests/test_cognitoidentity/test_server.py
@@ -48,6 +48,5 @@ def test_get_id():
         },
     )
 
-    print(res.data)
     json_data = json.loads(res.data.decode("utf-8"))
     assert ":" in json_data["IdentityId"]
Repository: getmoto/moto
Issue: Wrong IAM get_user_policy() response

The result given back from get_user_policy() is wrong. 'PolicyDocument' contains the internal dict that is used by moto instead of the clean policy document.
```
import json
from moto import mock_iam
import boto3

iam = boto3.client('iam')
iam.create_user(UserName='testuser')
iam.put_user_policy(
    UserName='testuser',
    PolicyName='testpolicy',
    PolicyDocument=json.dumps({'key': 'value'}))
result = iam.get_user_policy(
    UserName='testuser', PolicyName='testpolicy')
print result
```

Results in:
```
{u'UserName': 'testuser', u'PolicyName': 'testpolicy', u'PolicyDocument': '\\n      {u\\'policy_document\\': u\\'{"key": "value"}\\', u\\'user_name\\': u\\'testuser\\', u\\'policy_name\\': u\\'testpolicy\\'}\\n      ', 'ResponseMetadata': {'RetryAttempts': 0, 'HTTPStatusCode': 200, 'RequestId': '7a62c49f-347e-4fc4-9331-6e8eEXAMPLE', 'HTTPHeaders': {u'Content-Type': u'text/plain', u'server': u'amazon.com'}}}
```

Changed files:
moto/iam/responses.py

diff --git a/moto/iam/responses.py b/moto/iam/responses.py
index 9931cb8d0..786afab08 100644
--- a/moto/iam/responses.py
+++ b/moto/iam/responses.py
@@ -407,7 +407,7 @@ class IamResponse(BaseResponse):
         return template.render(
             user_name=user_name,
             policy_name=policy_name,
-            policy_document=policy_document
+            policy_document=policy_document.get('policy_document')
         )
 
     def list_user_policies(self):
Repository: getmoto/moto
Issue: [bug] Route53.list_resource_record_sets not returning `IsTruncated`

`boto3` documentation specifies that `list_resource_record_sets` should return:
```python
'IsTruncated': True|False,
```
to indicate if results were truncated.

AWS API always returns this field, whether records are truncated or not. We rely on this field to know if we need to fetch more results, and using `@mock_route53` around this code fails due to missing field.

https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/route53.html#Route53.Client.list_resource_record_sets

Changed files:
moto/route53/responses.py, tests/test_route53/test_route53.py

diff --git a/moto/route53/responses.py b/moto/route53/responses.py
index 3e688b65d..077c89a2c 100644
--- a/moto/route53/responses.py
+++ b/moto/route53/responses.py
@@ -271,6 +271,7 @@ LIST_RRSET_RESPONSE = """<ListResourceRecordSetsResponse xmlns="https://route53.
       {{ record_set.to_xml() }}
    {% endfor %}
    </ResourceRecordSets>
+   <IsTruncated>false</IsTruncated>
 </ListResourceRecordSetsResponse>"""
 
 CHANGE_RRSET_RESPONSE = """<ChangeResourceRecordSetsResponse xmlns="https://route53.amazonaws.com/doc/2012-12-12/">
diff --git a/tests/test_route53/test_route53.py b/tests/test_route53/test_route53.py
index 0e9a1e2c0..746c78719 100644
--- a/tests/test_route53/test_route53.py
+++ b/tests/test_route53/test_route53.py
@@ -862,6 +862,8 @@ def test_list_resource_record_sets_name_type_filters():
         StartRecordName=all_records[start_with][1],
     )
 
+    response["IsTruncated"].should.equal(False)
+
     returned_records = [
         (record["Type"], record["Name"]) for record in response["ResourceRecordSets"]
     ]
Repository: getmoto/moto
Issue: EMR list_step responses don't contain start date in output

There is a bug in the LIST_STEP_TEMPLATE and other EMR templates around the start date for steps: the conditional looks at `ready_datetime` but then outputs `start_datetime`.

This from https://github.com/spulec/moto/blob/896f040fca975865c1d441d90016446c72db3ed4/moto/emr/responses.py#L794-L796

```
            {% if step.ready_datetime is not none %}
            <StartDateTime>{{ step.start_datetime.isoformat() }}</StartDateTime>
            {% endif %}
```

Nothing in the code looks at `step.ready_datetime` that I could see (use create, start, and end), so I'm guessing the conditional is wrong. This exists in a few other templates too.

Changed files:
moto/emr/responses.py, moto/emr/models.py, tests/test_emr/test_emr_boto3.py

diff --git a/moto/emr/models.py b/moto/emr/models.py
index 713b15b9f..d9ec2fd69 100644
--- a/moto/emr/models.py
+++ b/moto/emr/models.py
@@ -86,6 +86,9 @@ class FakeStep(BaseModel):
         self.start_datetime = None
         self.state = state
 
+    def start(self):
+        self.start_datetime = datetime.now(pytz.utc)
+
 
 class FakeCluster(BaseModel):
     def __init__(
@@ -204,6 +207,8 @@ class FakeCluster(BaseModel):
 
         self.start_cluster()
         self.run_bootstrap_actions()
+        if self.steps:
+            self.steps[0].start()
 
     @property
     def instance_groups(self):
diff --git a/moto/emr/responses.py b/moto/emr/responses.py
index 94847ec8b..38b9774e1 100644
--- a/moto/emr/responses.py
+++ b/moto/emr/responses.py
@@ -835,7 +835,7 @@ LIST_STEPS_TEMPLATE = """<ListStepsResponse xmlns="http://elasticmapreduce.amazo
             {% if step.end_datetime is not none %}
             <EndDateTime>{{ step.end_datetime.isoformat() }}</EndDateTime>
             {% endif %}
-            {% if step.ready_datetime is not none %}
+            {% if step.start_datetime is not none %}
             <StartDateTime>{{ step.start_datetime.isoformat() }}</StartDateTime>
             {% endif %}
           </Timeline>
diff --git a/tests/test_emr/test_emr_boto3.py b/tests/test_emr/test_emr_boto3.py
index 212444abf..d849247bd 100644
--- a/tests/test_emr/test_emr_boto3.py
+++ b/tests/test_emr/test_emr_boto3.py
@@ -752,7 +752,9 @@ def test_steps():
         # StateChangeReason
         x["Status"]["Timeline"]["CreationDateTime"].should.be.a("datetime.datetime")
         # x['Status']['Timeline']['EndDateTime'].should.be.a('datetime.datetime')
-        # x['Status']['Timeline']['StartDateTime'].should.be.a('datetime.datetime')
+        # Only the first step will have started - we don't know anything about when it finishes, so the second step never starts
+        if x["Name"] == "My wordcount example":
+            x["Status"]["Timeline"]["StartDateTime"].should.be.a("datetime.datetime")
 
         x = client.describe_step(ClusterId=cluster_id, StepId=x["Id"])["Step"]
         x["ActionOnFailure"].should.equal("TERMINATE_CLUSTER")
Repository: getmoto/moto
Issue: AWS Config S3 ACLs missing owner

It looks like AWS Config for S3 has a slightly different behavior from when I initially wrote the capability a while back. AWS Config is now including the default account owner ACL in the grantees now.

The following lines need to be removed:
https://github.com/spulec/moto/blob/master/moto/s3/models.py#L439-L441

I will make a PR soon to fix.

Changed files:
tests/test_s3/test_s3.py, moto/s3/models.py

diff --git a/moto/s3/models.py b/moto/s3/models.py
index d86821c4f..ba0366153 100644
--- a/moto/s3/models.py
+++ b/moto/s3/models.py
@@ -436,10 +436,6 @@ class FakeAcl(BaseModel):
             )
             for permission in permissions:
                 for grantee in grant.grantees:
-                    # Config does not add the owner if its permissions are FULL_CONTROL:
-                    if permission == "FULL_CONTROL" and grantee.id == OWNER:
-                        continue
-
                     if grantee.uri:
                         grant_list.append(
                             {
diff --git a/tests/test_s3/test_s3.py b/tests/test_s3/test_s3.py
index e2ba9d8d8..f32e8c560 100644
--- a/tests/test_s3/test_s3.py
+++ b/tests/test_s3/test_s3.py
@@ -4648,7 +4648,15 @@ def test_s3_acl_to_config_dict():
 
     # Get the config dict with nothing other than the owner details:
     acls = s3_config_query.backends["global"].buckets["logbucket"].acl.to_config_dict()
-    assert acls == {"grantSet": None, "owner": {"displayName": None, "id": OWNER}}
+    owner_acl = {
+        "grantee": {"id": OWNER, "displayName": None},
+        "permission": "FullControl",
+    }
+    assert acls == {
+        "grantSet": None,
+        "owner": {"displayName": None, "id": OWNER},
+        "grantList": [owner_acl],
+    }
 
     # Add some Log Bucket ACLs:
     log_acls = FakeAcl(
@@ -4672,6 +4680,13 @@ def test_s3_acl_to_config_dict():
         "grantList": [
             {"grantee": "LogDelivery", "permission": "Write"},
             {"grantee": "LogDelivery", "permission": "ReadAcp"},
+            {
+                "grantee": {
+                    "displayName": None,
+                    "id": "75aa57f09aa0c8caeab4f8c24e99d10f8e7faeebf76c078efc7c6caea54ba06a",
+                },
+                "permission": "FullControl",
+            },
         ],
         "owner": {"displayName": None, "id": OWNER},
     }
@@ -4791,6 +4806,15 @@ def test_s3_config_dict():
         json.loads(bucket1_result["supplementaryConfiguration"]["AccessControlList"])
     ) == {
         "grantSet": None,
+        "grantList": [
+            {
+                "grantee": {
+                    "displayName": None,
+                    "id": "75aa57f09aa0c8caeab4f8c24e99d10f8e7faeebf76c078efc7c6caea54ba06a",
+                },
+                "permission": "FullControl",
+            },
+        ],
         "owner": {
             "displayName": None,
             "id": "75aa57f09aa0c8caeab4f8c24e99d10f8e7faeebf76c078efc7c6caea54ba06a",
Repository: getmoto/moto
Issue: CF error during template validation: TypeError: decode() takes 1 positional argument but 2 were given

Full error:
```
File "/home/travis/build/spulec/moto/moto/cloudformation/responses.py", line 399, in validate_template
    cfn_lint = self.cloudformation_backend.validate_template(template_body)
  File "/home/travis/build/spulec/moto/moto/cloudformation/models.py", line 748, in validate_template
    return validate_template_cfn_lint(template)
  File "/home/travis/build/spulec/moto/moto/cloudformation/utils.py", line 74, in validate_template_cfn_lint
    template, matches = decode.decode(abs_filename, False)
TypeError: decode() takes 1 positional argument but 2 were given
```

Error occurs after `cfn-lint` 0.39.0 was released. 

Travis build that highlights the errors: https://travis-ci.org/github/spulec/moto/jobs/738443110

Specific PR that changed the method-signature: https://github.com/aws-cloudformation/cfn-python-lint/pull/1580/files

PR incoming to fix this

Changed files:
moto/cloudformation/utils.py

diff --git a/moto/cloudformation/utils.py b/moto/cloudformation/utils.py
index 54c338b9b..d025af5fd 100644
--- a/moto/cloudformation/utils.py
+++ b/moto/cloudformation/utils.py
@@ -71,7 +71,12 @@ def validate_template_cfn_lint(template):
     abs_filename = os.path.abspath(filename)
 
     # decode handles both yaml and json
-    template, matches = decode.decode(abs_filename, False)
+    try:
+        template, matches = decode.decode(abs_filename, False)
+    except TypeError:
+        # As of cfn-lint 0.39.0, the second argument (ignore_bad_template) was dropped
+        # https://github.com/aws-cloudformation/cfn-python-lint/pull/1580
+        template, matches = decode.decode(abs_filename)
 
     # Set cfn-lint to info
     core.configure_logging(None)
Repository: getmoto/moto
Issue: Fails to install cryptography for `moto-1.3.15`

Inside a python:3.8-slim docker container, `pip install moto` does not install `cryptography` on the latest moto release (moto-1.3.15). This causes subsequent commands to fail with `ModuleNotFoundError: No module named 'cryptography'` when invoking `moto` mocks.

To see this, jump into a fresh docker:
`docker run --rm -it python:3.8-slim /bin/bash`

Then inside run:
```
pip install moto
pip list
```
And note that `cryptography` is not installed.

Now run:
```
pip install moto==1.3.14
pip list
```

And note that `cryptography` is now installed.

An example of the failures seen when using the new release (ie. having only run `pip install moto`):
```
/usr/local/lib/python3.8/site-packages/moto/iam/__init__.py:2: in <module>
    from .models import iam_backend
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

    from __future__ import unicode_literals
    import base64
    import hashlib
    import os
    import random
    import string
    import sys
    from datetime import datetime
    import json
    import re
    
>   from cryptography import x509
E   ModuleNotFoundError: No module named 'cryptography'

/usr/local/lib/python3.8/site-packages/moto/iam/models.py:12: ModuleNotFoundError
```

Changed files:
setup.py

diff --git a/setup.py b/setup.py
index 92ab7a5de..fe2896191 100755
--- a/setup.py
+++ b/setup.py
@@ -99,25 +99,27 @@ all_extra_deps = [
     _dep_sshpubkeys_py2,
     _dep_sshpubkeys_py3,
 ]
+all_server_deps = all_extra_deps + ['flask']
 
 # TODO: do we want to add ALL services here?
 # i.e. even those without extra dependencies.
 # Would be good for future-compatibility, I guess.
 extras_per_service = {
-    "ec2": [_dep_cryptography, _dep_sshpubkeys_py2, _dep_sshpubkeys_py3],
     'acm': [_dep_cryptography],
-    'iam': [_dep_cryptography],
-    'cloudformation': [_dep_PyYAML, _dep_cfn_lint],
-    'cognitoidp': [_dep_python_jose, _dep_python_jose_ecdsa_pin],
     'awslambda': [_dep_docker],
     'batch': [_dep_docker],
+    'cloudformation': [_dep_PyYAML, _dep_cfn_lint],
+    'cognitoidp': [_dep_python_jose, _dep_python_jose_ecdsa_pin],
+    "ec2": [_dep_cryptography, _dep_sshpubkeys_py2, _dep_sshpubkeys_py3],
+    'iam': [_dep_cryptography],
     'iotdata': [_dep_jsondiff],
+    's3': [_dep_cryptography],
     'xray': [_dep_aws_xray_sdk],
 }
 
 extras_require = {
     'all': all_extra_deps,
-    'server': ['flask'],
+    'server': all_server_deps,
 }
 
 extras_require.update(extras_per_service)
Repository: platformio/platformio-core
Issue: Using C++ with the STM32F4 Discovery causes linker errors, what am I doing wrong?

I've created a project using the **platformio init --board=disco_f407vg** command, and then proceeded to write a main.cpp. Everything seemed to work fine at first but when I try to use **new** or **delete** I get linker errors. Specifically I have a line **int \\* testInt = new int;** which then causes **main.cpp:12: undefined reference to `operator new(unsigned int)'** (where line 12 is the line containing the new call).

I'm guessing I still have to add some setting to the platform.ini to configure it for full C++ support, but I can't find anything about such a setting in the documentation. What am I missing?

Thanks for the help (also thanks for building this software, I don't think I've ever had a toolchain and bsp install this quickly and easily!)


Changed files:
platformio/builder/scripts/ststm32.py

diff --git a/platformio/builder/scripts/ststm32.py b/platformio/builder/scripts/ststm32.py
index 0855457d..c1622028 100644
--- a/platformio/builder/scripts/ststm32.py
+++ b/platformio/builder/scripts/ststm32.py
@@ -53,6 +53,8 @@ env.Append(
         "${BOARD_OPTIONS['build']['variant'].upper()}"
     ],
 
+    LIBS=["stdc++", "nosys"],
+
     LINKFLAGS=[
         "-nostartfiles",
         "-nostdlib"
Repository: espnet/espnet
Issue: Freeze modules bug?

https://github.com/espnet/espnet/blob/25862dd93081746ac623720f31f4f0f323c9750e/espnet/tts/pytorch_backend/tts.py#L331-L334

Do you think to freeze the module of the model, the line should be change into:
 if any(mod.startswith(key) for key in args.freeze_mods): 
?



Changed files:
espnet/tts/pytorch_backend/tts.py

diff --git a/espnet/tts/pytorch_backend/tts.py b/espnet/tts/pytorch_backend/tts.py
index 9d4c870d7..01395199e 100644
--- a/espnet/tts/pytorch_backend/tts.py
+++ b/espnet/tts/pytorch_backend/tts.py
@@ -330,7 +330,8 @@ def train(args):
     # freeze modules, if specified
     if args.freeze_mods:
         for mod, param in model.state_dict().items():
-            if any(key.startswith(mod) for key in args.freeze_mods):
+            if any(mod.startswith(key) for key in args.freeze_mods):
+                logging.info(f"{mod} is frozen not to be updated.")
                 param.requires_grad = False
 
     # Setup an optimizer
Repository: espnet/espnet
Issue: [Feature Request]: allow to specify which gpu to use

As far as I could see, there is no such option. To clarify, this is useful when running a script on a machine with more than one GPU, having a flag such as `--gpu 1` or `--device cuda:1` would be of great help!

Thanks for all the work!

Changed files:
espnet/bin/lm_train.py, espnet/bin/st_train.py, espnet/bin/mt_train.py, espnet/bin/tts_train.py

diff --git a/espnet/bin/lm_train.py b/espnet/bin/lm_train.py
index 724b9e3cd..efe99d4b6 100755
--- a/espnet/bin/lm_train.py
+++ b/espnet/bin/lm_train.py
@@ -149,6 +149,7 @@ def main(cmd_args):
                 ngpu = 0
             else:
                 ngpu = len(p.stderr.decode().split('\\n')) - 1
+        args.ngpu = ngpu
     else:
         ngpu = args.ngpu
     logging.info(f"ngpu: {ngpu}")
diff --git a/espnet/bin/mt_train.py b/espnet/bin/mt_train.py
index 5ab84d9dd..5ee8234b0 100755
--- a/espnet/bin/mt_train.py
+++ b/espnet/bin/mt_train.py
@@ -239,6 +239,7 @@ def main(cmd_args):
                 ngpu = 0
             else:
                 ngpu = len(p.stderr.decode().split('\\n')) - 1
+        args.ngpu = ngpu
     else:
         if is_torch_1_2_plus and args.ngpu != 1:
             logging.debug("There are some bugs with multi-GPU processing in PyTorch 1.2+" +
diff --git a/espnet/bin/st_train.py b/espnet/bin/st_train.py
index c348da045..81e1adf40 100755
--- a/espnet/bin/st_train.py
+++ b/espnet/bin/st_train.py
@@ -275,6 +275,7 @@ def main(cmd_args):
                 ngpu = 0
             else:
                 ngpu = len(p.stderr.decode().split('\\n')) - 1
+        args.ngpu = ngpu
     else:
         if is_torch_1_2_plus and args.ngpu != 1:
             logging.debug("There are some bugs with multi-GPU processing in PyTorch 1.2+" +
diff --git a/espnet/bin/tts_train.py b/espnet/bin/tts_train.py
index d03663ff3..ce25f98bf 100755
--- a/espnet/bin/tts_train.py
+++ b/espnet/bin/tts_train.py
@@ -178,6 +178,7 @@ def main(cmd_args):
                 ngpu = 0
             else:
                 ngpu = len(p.stderr.decode().split('\\n')) - 1
+        args.ngpu = ngpu
     else:
         ngpu = args.ngpu
     logging.info(f"ngpu: {ngpu}")
Repository: espnet/espnet
Issue: A bug in the implementation of DNN-based WPE?

Hi, I was just checking the code in the front-end part.
I found that at the end of `dnn_wpe.py`, a non-inplace operation is used without using the returned value. Should `masked_fill` be replaced with `masked_fill_`?

https://github.com/espnet/espnet/blob/33ef80069c6f42bfbccffe2ea2f8d812f1cbeaaa/espnet/nets/pytorch_backend/frontends/dnn_wpe.py#L82

Changed files:
espnet/nets/pytorch_backend/frontends/dnn_wpe.py

diff --git a/espnet/nets/pytorch_backend/frontends/dnn_wpe.py b/espnet/nets/pytorch_backend/frontends/dnn_wpe.py
index d3cb5670c..892e65fcb 100644
--- a/espnet/nets/pytorch_backend/frontends/dnn_wpe.py
+++ b/espnet/nets/pytorch_backend/frontends/dnn_wpe.py
@@ -79,7 +79,7 @@ class DNN_WPE(torch.nn.Module):
                 taps=self.taps, delay=self.delay,
                 inverse_power=self.inverse_power)
 
-            enhanced.masked_fill(make_pad_mask(ilens, enhanced.real), 0)
+            enhanced.masked_fill_(make_pad_mask(ilens, enhanced.real), 0)
 
         # (B, F, C, T) -> (B, T, C, F)
         enhanced = enhanced.permute(0, 3, 2, 1)
Repository: espnet/espnet
Issue: V.6.0.0 asr_train with transformer raise error

Given that the argument `atype` was moved to e2e_asr.py, the asr.py will raise error in chainer backend when the config is set to train the transformer.

```
Traceback (most recent call last):
  File "/export/db/espnet/egs/voxforge/asr1/../../../espnet/bin/asr_train.py", line 341, in <module>
    main(sys.argv[1:])
  File "/export/db/espnet/egs/voxforge/asr1/../../../espnet/bin/asr_train.py", line 325, in main
    train(args)
  File "/export/db/espnet/espnet/asr/chainer_backend/asr.py", line 81, in train
    if args.atype not in ['noatt', 'dot', 'location']:
AttributeError: 'Namespace' object has no attribute 'atype'
```

not sure if it is required to remove:

```python
    # check attention type
    if args.atype not in ['noatt', 'dot', 'location']:
        raise NotImplementedError('chainer supports only noatt, dot, and location attention.')
```
or not move to another part. Let me know to submit a PR

Changed files:
espnet/nets/chainer_backend/rnn/attentions.py, espnet/asr/chainer_backend/asr.py

diff --git a/espnet/asr/chainer_backend/asr.py b/espnet/asr/chainer_backend/asr.py
index f891775a6..371105682 100644
--- a/espnet/asr/chainer_backend/asr.py
+++ b/espnet/asr/chainer_backend/asr.py
@@ -77,10 +77,6 @@ def train(args):
     logging.info('#input dims : ' + str(idim))
     logging.info('#output dims: ' + str(odim))
 
-    # check attention type
-    if args.atype not in ['noatt', 'dot', 'location']:
-        raise NotImplementedError('chainer supports only noatt, dot, and location attention.')
-
     # specify attention, CTC, hybrid mode
     if args.mtlalpha == 1.0:
         mtl_mode = 'ctc'
diff --git a/espnet/nets/chainer_backend/rnn/attentions.py b/espnet/nets/chainer_backend/rnn/attentions.py
index f2a5e848c..fd26e4371 100644
--- a/espnet/nets/chainer_backend/rnn/attentions.py
+++ b/espnet/nets/chainer_backend/rnn/attentions.py
@@ -2,9 +2,7 @@ import chainer
 import chainer.functions as F
 import chainer.links as L
 
-import logging
 import numpy as np
-import sys
 
 from espnet.nets.chainer_backend.nets_utils import linear_tensor
 
@@ -253,7 +251,5 @@ def att_for(args):
     elif args.atype == 'noatt':
         att = NoAtt()
     else:
-        logging.error(
-            "Error: need to specify an appropriate attention architecture")
-        sys.exit()
+        raise NotImplementedError('chainer supports only noatt, dot, and location attention.')
     return att
Repository: espnet/espnet
Issue: matplotlib.use('Agg') fail

It result in plot fail 
```
_tkinter.TclError: no display name and no $DISPLAY environment variable
```
I fixed this by applying a patch on `espnet/nets/pytorch_backend/transformer/plot.py`
```
@@ -1,5 +1,6 @@
 import logging
-
+import matplotlib
+matplotlib.use('Agg')
 import matplotlib.pyplot as plt

 from espnet.asr import asr_utils
```

Changed files:
espnet/nets/pytorch_backend/transformer/plot.py

diff --git a/espnet/nets/pytorch_backend/transformer/plot.py b/espnet/nets/pytorch_backend/transformer/plot.py
index 66985df55..af5f0ef6e 100644
--- a/espnet/nets/pytorch_backend/transformer/plot.py
+++ b/espnet/nets/pytorch_backend/transformer/plot.py
@@ -1,8 +1,7 @@
 import logging
 
-import matplotlib.pyplot as plt
-
 from espnet.asr import asr_utils
+import matplotlib.pyplot as plt
 
 
 def _plot_and_save_attention(att_w, filename):
Repository: espnet/espnet
Issue: CSJ recipe with PyTorch backend

when using PyTorch as the backend, the model outputs only \\<EOS\\> token in the decoding phase, while the Chainer backend is fine (under the same hyperparameter setting). 

Changed files:
espnet/nets/e2e_asr_th.py

diff --git a/espnet/nets/e2e_asr_th.py b/espnet/nets/e2e_asr_th.py
index b182efafd..708e7e950 100644
--- a/espnet/nets/e2e_asr_th.py
+++ b/espnet/nets/e2e_asr_th.py
@@ -2320,7 +2320,7 @@ class Decoder(torch.nn.Module):
         pad_bo = to_cuda(self, torch.LongTensor([i * n_bo for i in six.moves.range(batch)]).view(-1, 1))
         pad_o = to_cuda(self, torch.LongTensor([i * self.odim for i in six.moves.range(n_bb)]).view(-1, 1))
 
-        max_hlen = max(hlens)
+        max_hlen = int(max(hlens))
         if recog_args.maxlenratio == 0:
             maxlen = max_hlen
         else:
Repository: espnet/espnet
Issue: espnet2 inference error without language model

If not using a language model, the espnet2 asr_inference.py causes the following error. 

File "espnet2/espnet2/bin/asr_inference.py", line 152, in __init__
self.lm_train_args = lm_train_args
UnboundLocalError: local variable 'lm_train_args' referenced before assignment


Changed files:
espnet2/bin/asr_inference.py

diff --git a/espnet2/bin/asr_inference.py b/espnet2/bin/asr_inference.py
index 61e657b6e..6c99fe0f2 100755
--- a/espnet2/bin/asr_inference.py
+++ b/espnet2/bin/asr_inference.py
@@ -147,7 +147,6 @@ class Speech2Text:
 
         self.asr_model = asr_model
         self.asr_train_args = asr_train_args
-        self.lm_train_args = lm_train_args
         self.converter = converter
         self.tokenizer = tokenizer
         self.beam_search = beam_search
Repository: espnet/espnet
Issue: error in training stage "Expected all tensors to be on the same device, but found at least two devices, cuda:0 and cpu!

Hello guys!
we are running the recipe of ljspeech of version 0.8.0 but on our data set, we are using google colaboratory. At the stage of training we are getting this error "Expected all tensors to be on the same device, but found at least two devices, cuda:0 and cpu!". Any help ? 
log file is attached.
[train.log](https://github.com/espnet/espnet/files/5044468/train.log)

Thanks in advance

Changed files:
espnet/nets/pytorch_backend/e2e_tts_tacotron2.py

diff --git a/espnet/nets/pytorch_backend/e2e_tts_tacotron2.py b/espnet/nets/pytorch_backend/e2e_tts_tacotron2.py
index 90e28eb59..6c0c64203 100644
--- a/espnet/nets/pytorch_backend/e2e_tts_tacotron2.py
+++ b/espnet/nets/pytorch_backend/e2e_tts_tacotron2.py
@@ -122,7 +122,7 @@ class GuidedAttentionLoss(torch.nn.Module):
 
         """
         grid_x, grid_y = torch.meshgrid(torch.arange(olen), torch.arange(ilen))
-        grid_x, grid_y = grid_x.float(), grid_y.float()
+        grid_x, grid_y = grid_x.float().to(olen.device), grid_y.float().to(ilen.device)
         return 1.0 - torch.exp(
             -((grid_y / ilen - grid_x / olen) ** 2) / (2 * (sigma ** 2))
         )
Repository: espnet/espnet
Issue: Espnet2 ASR DataParallel API mismatching?

In `espnet/espnet2/train/trainer.py:250,17` 
It seems that `torch.nn.parallel.DataParallel` doesn't have a parameter `find_unused_parameters`.
Is it a bug?

Changed files:
espnet2/train/trainer.py

diff --git a/espnet2/train/trainer.py b/espnet2/train/trainer.py
index 019c93e38..5d86bbb7d 100644
--- a/espnet2/train/trainer.py
+++ b/espnet2/train/trainer.py
@@ -247,7 +247,6 @@ class Trainer:
             dp_model = torch.nn.parallel.DataParallel(
                 model,
                 device_ids=list(range(distributed_option.ngpu)),
-                find_unused_parameters=trainer_options.unused_parameters,
             )
         else:
             # NOTE(kamo): DataParallel also should work with ngpu=1,
Repository: espnet/espnet
Issue: AttributeError: 'NoneType' object has no attribute 'run'

I train conformer model using aishell recipe(ESPnet2) , but when in training stage , I got this:

2022-05-26 21:31:26,160 (trainer:328) INFO: 50epoch results: [train] iter_time=6.764e-05, forward_time=0.043, loss_ctc=0.331, loss_att=0.502, acc=0.993, loss=0.225, backward_time=0.040, optim_step_time=0.038, optim0_lr0=1.133e-04, train_time=0.264, time=51 minutes and 57 seconds, total_count=1181200, gpu_max_cached_mem_GB=5.084, [valid] loss_ctc=6.020, cer_ctc=0.112, loss_att=3.802, acc=0.916, cer=0.107, wer=0.466, loss=4.467, time=23.6 seconds, total_count=25950, gpu_max_cached_mem_GB=5.084, [att_plot] time=31.79 seconds, total_count=0, gpu_max_cached_mem_GB=5.084
2022-05-26 21:32:34,718 (trainer:374) INFO: There are no improvements in this epoch
2022-05-26 21:32:34,731 (trainer:449) INFO: The training was finished at 50 epochs 
2022-05-26 21:32:34,755 (average_nbest_models:70) INFO: Averaging 10best models: criterion="valid.acc": exp/asr_train_asr_conformer_raw_zh_char/valid.acc.ave_10best.pth
Traceback (most recent call last):
  File "/Share/lli/espnet/tools/anaconda/envs/espnet/lib/python3.7/runpy.py", line 193, in _run_module_as_main
    "__main__", mod_spec)
  File "/Share/lli/espnet/tools/anaconda/envs/espnet/lib/python3.7/runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "/Share/lli/espnet/espnet2/bin/asr_train.py", line 23, in <module>
    main()
  File "/Share/lli/espnet/espnet2/bin/asr_train.py", line 19, in main
    ASRTask.main(cmd=cmd)
  File "/Share/lli/espnet/espnet2/tasks/abs_task.py", line 1011, in main
    cls.main_worker(args)
  File "/Share/lli/espnet/espnet2/tasks/abs_task.py", line 1318, in main_worker
    if wandb.run:
AttributeError: 'NoneType' object has no attribute 'run'
Accounting: time=170861 threads=1
Ended (code 1) at Thu May 26 21:35:06 CST 2022, elapsed time 170861 seconds

Basic environments:
OS information: Linux
python version: 3.7.4
espnet version: 202204
pytorch version 1.6.0
Task information:

Task: ASR
Recipe: aishell
ESPnet2
Could you please help me?

Changed files:
espnet2/tasks/abs_task.py

diff --git a/espnet2/tasks/abs_task.py b/espnet2/tasks/abs_task.py
index 06d2663ef..d0c6f7519 100644
--- a/espnet2/tasks/abs_task.py
+++ b/espnet2/tasks/abs_task.py
@@ -1315,7 +1315,7 @@ class AbsTask(ABC):
                 distributed_option=distributed_option,
             )
 
-            if wandb.run:
+            if args.use_wandb and wandb.run:
                 wandb.finish()
 
     @classmethod
Repository: espnet/espnet
Issue: TTS lid=true bug

@kan-bayashi  Hi when I set use_lid=true , the following error occurs, like the support for lid is incomplete
`RuntimeError: The data-name must be one of ('text', 'speech', 'spembs', 'sids', 'durations', 'pitch', 'energy') for GANTTSTask: "lids" is not allowed.`

Changed files:
espnet2/tasks/gan_tts.py, espnet2/tasks/tts.py

diff --git a/espnet2/tasks/gan_tts.py b/espnet2/tasks/gan_tts.py
index bfdc34340..d7eb4a039 100644
--- a/espnet2/tasks/gan_tts.py
+++ b/espnet2/tasks/gan_tts.py
@@ -221,7 +221,9 @@ class GANTTSTask(AbsTask):
     ]:
         assert check_argument_types()
         return CommonCollateFn(
-            float_pad_value=0.0, int_pad_value=0, not_sequence=["spembs", "sids"]
+            float_pad_value=0.0,
+            int_pad_value=0,
+            not_sequence=["spembs", "sids", "lids"],
         )
 
     @classmethod
@@ -260,10 +262,25 @@ class GANTTSTask(AbsTask):
         cls, train: bool = True, inference: bool = False
     ) -> Tuple[str, ...]:
         if not inference:
-            retval = ("spembs", "sids", "durations", "pitch", "energy")
+            retval = (
+                "spembs",
+                "durations",
+                "pitch",
+                "energy",
+                "sids",
+                "lids",
+            )
         else:
             # Inference mode
-            retval = ("spembs", "sids", "speech", "durations", "pitch", "energy")
+            retval = (
+                "spembs",
+                "speech",
+                "durations",
+                "pitch",
+                "energy",
+                "sids",
+                "lids",
+            )
         return retval
 
     @classmethod
diff --git a/espnet2/tasks/tts.py b/espnet2/tasks/tts.py
index df21faf93..ecaf98177 100644
--- a/espnet2/tasks/tts.py
+++ b/espnet2/tasks/tts.py
@@ -260,10 +260,25 @@ class TTSTask(AbsTask):
         cls, train: bool = True, inference: bool = False
     ) -> Tuple[str, ...]:
         if not inference:
-            retval = ("spembs", "durations", "pitch", "energy", "sids", "lids")
+            retval = (
+                "spembs",
+                "durations",
+                "pitch",
+                "energy",
+                "sids",
+                "lids",
+            )
         else:
             # Inference mode
-            retval = ("spembs", "speech", "durations", "sids", "lids")
+            retval = (
+                "spembs",
+                "speech",
+                "durations",
+                "pitch",
+                "energy",
+                "sids",
+                "lids",
+            )
         return retval
 
     @classmethod
Repository: espnet/espnet
Issue: RNN-T ALSD beam search decoder bug ???

https://github.com/espnet/espnet/blob/682dad150bb13c7d852600583c53ce8d24fd1d6e/espnet/nets/pytorch_backend/transducer/utils.py#L296

return `final` rather than `hyps`  here ?

Changed files:
espnet/nets/pytorch_backend/transducer/utils.py

diff --git a/espnet/nets/pytorch_backend/transducer/utils.py b/espnet/nets/pytorch_backend/transducer/utils.py
index 185362d28..d8bf3bfe3 100644
--- a/espnet/nets/pytorch_backend/transducer/utils.py
+++ b/espnet/nets/pytorch_backend/transducer/utils.py
@@ -293,7 +293,7 @@ def recombine_hyps(hyps: List[Hypothesis]) -> List[Hypothesis]:
         else:
             final.append(hyp)
 
-    return hyps
+    return final
 
 
 def pad_sequence(labels: List[int], pad_id: int) -> List[int]:
Repository: espnet/espnet
Issue: Fix accent phrase border in pyopenjtalk_g2p_prosody

In pyopenjtalk_g2p_prosody of espnet/espnet2/text/phoneme_tokenizer.py, the condition of the accent phrase boundary on the 163st line is
if a3 == 1 and a2_next == 1:
Since there is no distinction between consonants and vowels, the delimiter'#' will be inserted between the consonants and vowels. 
Add the case where the phoneme corresponds to a vowel,  syllabic nasal/N/ and choked sounds/cl/ to the condition,
if a3 == 1 and a2_next == 1 and p3 in "aeiouAEIOUNcl":
Shouldn't it be?
Due to this change, the output example of g2p changes from
e.g. こ、こんにちは -> [^, k, #, o, _, k, o, [, N, n, i, ch, i, w, a, $]
to
e.g. こ、こんにちは -> [^, k, o, _, k, o, [, N, n, i, ch, i, w, a, $]

Changed files:
espnet2/text/phoneme_tokenizer.py

diff --git a/espnet2/text/phoneme_tokenizer.py b/espnet2/text/phoneme_tokenizer.py
index d4246151d..03327643f 100644
--- a/espnet2/text/phoneme_tokenizer.py
+++ b/espnet2/text/phoneme_tokenizer.py
@@ -160,7 +160,7 @@ def pyopenjtalk_g2p_prosody(text: str, drop_unvoiced_vowels: bool = True) -> Lis
 
         a2_next = _numeric_feature_by_regex(r"\\+(\\d+)\\+", labels[n + 1])
         # accent phrase border
-        if a3 == 1 and a2_next == 1:
+        if a3 == 1 and a2_next == 1 and p3 in "aeiouAEIOUNcl":
             phones.append("#")
         # pitch falling
         elif a1 == 0 and a2_next == a2 + 1 and a2 != f1:
Repository: espnet/espnet
Issue: incorrect olens result for stft when win_length is not same as n_fft

In torch.stft, win_length is not used when calculating the number of frames, which is same as libriosa.stft,  see also http://librosa.org/doc/main/_modules/librosa/core/spectrum.html#stft.

In espnet2/layers/stft.py
```python
161        if ilens is not None:
162            if self.center:
163                pad = self.win_length // 2
164                ilens = ilens + 2 * pad
165
166            olens = (ilens - self.win_length) // self.hop_length + 1
```
should be
```python
161         if ilens is not None:
162             if self.center:
163                 pad = self.n_fft // 2
164                 ilens = ilens + 2 * pad
165
166             olens = (ilens - self.n_fft) // self.hop_length + 1
```

Changed files:
espnet2/layers/stft.py

diff --git a/espnet2/layers/stft.py b/espnet2/layers/stft.py
index 01bbce8ea..b888bfede 100644
--- a/espnet2/layers/stft.py
+++ b/espnet2/layers/stft.py
@@ -160,10 +160,10 @@ class Stft(torch.nn.Module, InversibleInterface):
 
         if ilens is not None:
             if self.center:
-                pad = self.win_length // 2
+                pad = self.n_fft // 2
                 ilens = ilens + 2 * pad
 
-            olens = (ilens - self.win_length) // self.hop_length + 1
+            olens = (ilens - self.n_fft) // self.hop_length + 1
             output.masked_fill_(make_pad_mask(olens, output, 1), 0.0)
         else:
             olens = None
Repository: espnet/espnet
Issue: Question on chunk shift in ChunkIterFactory.build_iter()

In the code, shift width is calculated as a ratio of utterance length as follows:
S = int(L * self.chunk_shift_ratio)

Shouldn't shift width be calculated as a ratio of chunk length like below ?
S = int(W * self.chunk_shift_ratio)


Changed files:
espnet2/iterators/chunk_iter_factory.py

diff --git a/espnet2/iterators/chunk_iter_factory.py b/espnet2/iterators/chunk_iter_factory.py
index 0e20b950f..f43703f9a 100644
--- a/espnet2/iterators/chunk_iter_factory.py
+++ b/espnet2/iterators/chunk_iter_factory.py
@@ -145,7 +145,7 @@ class ChunkIterFactory(AbsIterFactory):
             cache_chunks = cache_chunks_dict.setdefault(W, {})
 
             # Shift width to the next chunk
-            S = int(L * self.chunk_shift_ratio)
+            S = int(W * self.chunk_shift_ratio)
             # Number of chunks
             N = (L - W) // S + 1
             if shuffle:
Repository: espnet/espnet
Issue: Error in Chainer RNNLM language model training.

When I run the script of CSJ recipe without `--ngpu` option, error occured.
```
2018-07-27 22:33:54,922 (lm_chainer:145) INFO: chainer version = 4.3.0
2018-07-27 22:33:54,923 (lm_chainer:150) INFO: chainer seed = 1
2018-07-27 22:33:54,923 (lm_chainer:158) INFO: chainer type check is disabled
2018-07-27 22:33:54,923 (lm_chainer:170) WARNING: cudnn is not available
2018-07-27 22:34:00,204 (lm_chainer:181) INFO: #vocab = 5939
2018-07-27 22:34:00,204 (lm_chainer:182) INFO: #words in the training data = 6666818
2018-07-27 22:34:00,204 (lm_chainer:183) INFO: #words in the validation data = 6666818
2018-07-27 22:34:00,204 (lm_chainer:184) INFO: #iterations per epoch = 744
2018-07-27 22:34:00,204 (lm_chainer:185) INFO: #total iterations = 29762
Traceback (most recent call last):
  File "/home/christopher/gitrepos/espnet-1/egs/csj/asr1/../../../src/bin/lm_train.py", line 131, in <module>
    main()
  File "/home/christopher/gitrepos/espnet-1/egs/csj/asr1/../../../src/bin/lm_train.py", line 122, in main
    train(args)
  File "/home/christopher/gitrepos/espnet-1/src/lm/lm_chainer.py", line 242, in train
    x, t = convert.concat_examples(batch, gpu_id)
UnboundLocalError: local variable 'gpu_id' referenced before assignment
# Accounting: time=17 threads=1
# Ended (code 1) at Fri Jul 27 22:34:01 UTC 2018, elapsed time 17 seconds
```

This may be because `gpu_id` is defined [here](https://github.com/espnet/espnet/blob/master/src/lm/lm_chainer.py#L199) , but it does not executed when `gpu_id` equals to 0.

Changed files:
src/lm/lm_chainer.py

diff --git a/src/lm/lm_chainer.py b/src/lm/lm_chainer.py
index 2e4635e5a..095c00186 100644
--- a/src/lm/lm_chainer.py
+++ b/src/lm/lm_chainer.py
@@ -200,6 +200,8 @@ def train(args):
         gpu_id = 0
         chainer.cuda.get_device_from_id(gpu_id).use()
         model.to_gpu()
+    else:
+        gpu_id = -1
 
     # Save model conf to json
     model_conf = args.outdir + '/model.json'
Repository: espnet/espnet
Issue: Error with using compute-fbank-feats.py

Hello! I tried to use script compute-fbank-feats.py to compute fbank features from wav, and tried to use it according to its documentation https://espnet.github.io/espnet/apis/utils_py.html#compute-fbank-feats-py

as folllows:
```
python3.7 utils/compute-fbank-feats.py scp:wav.scp ark:out.ark
```

but got an error:

```
  File "utils/compute-fbank-feats.py", line 134, in <module>
    main()
  File "utils/compute-fbank-feats.py", line 128, in main
    fmax=args.fmax,
  File "/home/karina/.local/lib/python3.7/site-packages/espnet/transform/spectrogram.py", line 116, in logmelspectrogram
    x_stft, fs=fs, n_mels=n_mels, n_fft=n_fft, fmin=fmin, fmax=fmax, eps=eps
  File "/home/karina/.local/lib/python3.7/site-packages/espnet/transform/spectrogram.py", line 74, in stft2logmelspectrogram
    fmax = fs / 2 if fmax is None else fmax
TypeError: unsupported operand type(s) for /: 'NoneType' and 'int'
```

wav.scp contains this text:
```
0 test.wav
```

Does anyone have ideas how to solve this error?

Changed files:
utils/compute-fbank-feats.py

diff --git a/utils/compute-fbank-feats.py b/utils/compute-fbank-feats.py
index 72feb1800..d5defc7d8 100755
--- a/utils/compute-fbank-feats.py
+++ b/utils/compute-fbank-feats.py
@@ -118,7 +118,7 @@ def main():
 
             lmspc = logmelspectrogram(
                 x=array,
-                fs=args.fs,
+                fs=args.fs if args.fs is not None else rate,
                 n_mels=args.n_mels,
                 n_fft=args.n_fft,
                 n_shift=args.n_shift,
Repository: espnet/espnet
Issue: How we can perform greedy decoding for RNN_T ?

Hi,
I trained an RNNT model using vivos recipe. I performed the decoding using beam search successfully now I'm trying to perform the decoding with greedy search I thought I could do that by setting beam-size parameter to 1:

**# decoding parameters**
batch: 0
**beam-size: 1**
search-type: default
score-norm: True

 but I got this error:

  File "/home/selma/espnet/espnet/asr/pytorch_backend/asr.py", line 1074, in recog
    js[name], nbest_hyps, train_args.char_list
  File "/home/selma/espnet/espnet/asr/asr_utils.py", line 828, in add_results_to_json
    rec_text, rec_token, rec_tokenid, score = parse_hypothesis(hyp, char_list)
  File "/home/selma/espnet/espnet/asr/asr_utils.py", line 796, in parse_hypothesis
    tokenid_as_list = list(map(int, hyp["yseq"][1:]))
TypeError: string indices must be integers

So I would like to know how could I perform greedy decoding for my model.
Thanks in advance!


Changed files:
espnet/nets/e2e_asr_common.py, test/test_e2e_asr_sa_transducer.py, espnet/nets/beam_search_transducer.py

diff --git a/espnet/nets/beam_search_transducer.py b/espnet/nets/beam_search_transducer.py
index 9703d0299..697a9d035 100644
--- a/espnet/nets/beam_search_transducer.py
+++ b/espnet/nets/beam_search_transducer.py
@@ -158,7 +158,7 @@ class BeamSearchTransducer:
 
                 y, state, _ = self.decoder.score(hyp, cache, init_tensor)
 
-        return hyp
+        return [hyp]
 
     def default_beam_search(self, h: torch.Tensor) -> List[Hypothesis]:
         """Beam search implementation.
diff --git a/espnet/nets/e2e_asr_common.py b/espnet/nets/e2e_asr_common.py
index 9c462e568..32f61ad9a 100644
--- a/espnet/nets/e2e_asr_common.py
+++ b/espnet/nets/e2e_asr_common.py
@@ -309,7 +309,7 @@ class ErrorCalculatorTransducer(object):
 
         for b in six.moves.range(batchsize):
             nbest_hyps = self.beam_search(hs_pad[b])
-            batch_nbest.append(nbest_hyps)
+            batch_nbest.append(nbest_hyps[-1])
 
         ys_hat = [nbest_hyp.yseq[1:] for nbest_hyp in batch_nbest]
 
diff --git a/test/test_e2e_asr_sa_transducer.py b/test/test_e2e_asr_sa_transducer.py
index 98120b506..8810a0f7b 100644
--- a/test/test_e2e_asr_sa_transducer.py
+++ b/test/test_e2e_asr_sa_transducer.py
@@ -280,10 +280,7 @@ def test_sa_transducer_trainable_and_decodable(train_dic, recog_dic):
         nbest = model.recognize(x[0, : ilens[0]].numpy(), beam_search)
 
         print(y[0])
-        if recog_args.beam_size == 1:
-            print(nbest["yseq"][1:-1])
-        else:
-            print(nbest[0]["yseq"][1:-1])
+        print(nbest[0]["yseq"][1:-1])
 
 
 def test_calculate_plot_attention():